Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
12,400
65,574,711
Is there a way to run posqresql queries in a pandas dataframe?
<p>I have pandas dataframe like this :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>created_at</th> <th>lat</th> <th>long</th> <th>hex_ID</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>2020-10-13 15:12:18.682905</td> <td>28.690628</td> <td>77.323285</td> <td>883da1ab0bfffff</t...
<p>just use groupy in df.</p> <pre class="lang-py prettyprint-override"><code># 2020-10-13 15:12:18.682905 -&gt; 2020-10-13 15:00:00 df['created_at_n'] = df['created_at'].astype(str).str.split(':').str[0] + ':00:00' df.groupby(['created_at_n', 'hex_id'])['lat'].count() </code></pre>
sql|pandas|postgresql|time-series|pandas-groupby
0
12,401
63,697,275
Regex string for different versions
<p>I'm trying to isolate instances in a Pandas Dataframe where the version number is not equal to .0 —i.e., if there are versions 10.0, 10.1, and 10.2, I only want to select versions 10.1 and 10.2. Does anyone know the proper regex to accomplish this? Thanks!</p>
<ul> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">Boolean indexing</a></li> <li>Split the string on the <code>.</code> and look at the value at index 1</li> <li>It's not clear if this is a column of <code>str</code> or <code>float</code> types. <ul> <...
python|regex|pandas
1
12,402
63,581,028
model.compile() fails with every but 'accuracy' metric
<p>I am working on a simple MLP, and coded this:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense from keras import Input def get_stats_model(): model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(D...
<p>From the comments</p> <blockquote> <ol> <li>Creating a <code>Virtual Environment</code> and</li> <li><strong><code>Importing Keras</code></strong> using the code, <code>from tensorflow import keras</code></li> </ol> <p>has resolved the issue. (paraphrased from drops and Aniket Bote).</p> </blockquote>
python|tensorflow|keras
0
12,403
63,570,028
Training gets progressively slower over time
<p>This is the first time I'm experiencing this issue. I've been using this model for a while, but with less data. The problem is that in the first 3 epochs training took 11 sec/step (31k samples / 128 batch size) while in the 4-th epoch it took 18 sec/step. In the fifth it took about 45 sec/step. I'm using Keras and n...
<p><strong>Symptoms:</strong></p> <p>This seems to be a memory issue due to a leak. First, you are able to run the model in constant epoch time for a small batch BUT with complete data, the epoch times increase progressively (with increasing time/step too!). I am assuming that as you run out of memory, it is causing in...
tensorflow|keras
3
12,404
24,616,671
numpy and statsmodels give different values when calculating correlations, How to interpret this?
<p>I can't find a reason why calculating the correlation between two series A and B using <code>numpy.correlate</code> gives me different results than the ones I obtain using <code>statsmodels.tsa.stattools.ccf</code></p> <p>Here's an example of this difference I mention:</p> <pre><code>import numpy as np from matplo...
<p><code>statsmodels.tsa.stattools.ccf</code> is based on <code>np.correlate</code> but does some additional things to give the correlation in the statistical sense instead of the signal processing sense, see <a href="http://en.wikipedia.org/wiki/Cross-correlation">cross-correlation on Wikipedia</a>. What happens exact...
python|numpy|statsmodels|cross-correlation
10
12,405
30,256,670
Pandas plotting: ValueError: ordinal should be >= 1
<p>I have the following Series, called <code>sr</code>.</p> <pre><code>In [1]: sr Out[1]: 0 0 1 0 2 0 3 0 4 0 5 1 6 2 7 4 8 7 9 4 10 3 11 2 12 1 13 2 14 ...
<p>If you run <code>plt.clf()</code> this will clear the plot in memory and may allow the plotting to proceed (worked for me when I encountered this error after interrupting the plotting routine).</p>
python|pandas|matplotlib
4
12,406
53,365,640
Conditional Average from Pandas DataFrame
<p>I have a dataframe with multiple columns of real estate sales data. I would like to find the average price-per-square-foot <code>'ppsf'</code> for all 1bed-1bath sales by zip code. Here is my attempt (each key in the dict is a zip code):</p> <pre><code>bed1_bath1={} for zip in zip_codes: bed1_bath1[zip]= (df.lo...
<p><code>(df[(df['bed']==1) &amp; (df['bath']==1) &amp; (df['zip']==zip)])['ppsf'].mean()</code> would do it. You simply choose the column you are interested in before calculating the mean (so you will not even do the processing for the rest of the columns).</p>
python|pandas
4
12,407
53,363,994
convert PIL numpy 3d array to 2d luma values
<p>I've loaded an image using:</p> <pre><code>import numpy as np from PIL import Image imag = Image.open("image.png") I = np.asarray(imag) </code></pre> <p>Where the shape of <code>I</code> is <code>(951, 1200, 3)</code></p> <p>But I would like to average each pixel roughly to it's luma values (<code>(r*g*b)/3</...
<p>I think the easiest thing is to use Pillow's built-in conversion to Luminance as follows:</p> <pre><code>import numpy as np from PIL import Image # Load image and convert to luminance, and thence to Numpy array imag = Image.open("image.png").convert('L') I = np.asarray(imag) </code></pre>
python|numpy|python-imaging-library
0
12,408
53,590,379
Convert multiple xlsm files automatically to multiple csv files by using pandas
<p>I have 300 raw datas (.xlsm) and wanne to extract useful datas and turn them to csv files as input for subsequent neural network, now i try to implement them with 10 datas as example, i have sucessfully extracted the informations what i need, but i dont know how to convert them to csv files with the same name, for ...
<p>The easiest way of doing this is to get the filename from the excel and then use the os.path.join() method to save it to the directory you want.</p> <pre><code>directory = &quot;C:/Test&quot; for files in excel_files: csvfilename = (os.path.basename(file)[-1]).replace('.xlsm','.csv') newtempfile=os.path.joi...
python|pandas
0
12,409
17,416,669
Measuring increase in heap size after loading large object
<p>I'm interested to find out the increase in the total size of python's heap when a large object is loaded. heapy seems to be what I need, but I don't understand the results.</p> <p>I have a 350 MB pickle file with a pandas <code>DataFrame</code> in it, which contains about 2.5 million entries. When I load the file a...
<p>You could try <a href="http://pythonhosted.org/Pympler/classtracker.html#classtracker" rel="nofollow">pympler</a>, which worked for me the last time I checked. If you are just interested in the total memory increase and not for a specific class, you could you an OS specific call to get the total memory used. Eg, on ...
python|pandas|heapy
1
12,410
20,341,911
Numpy array __contains__ check
<p>I got an array of arrays:</p> <pre><code>temp = np.empty(5, dtype=np.ndarray) temp[0] = np.array([0,1]) </code></pre> <p>I want to check if <code>np.array([0,1]) in temp</code>, which in the above example clearly is but the code returns false. I also tried <code>temp.__contains__(np.array([0,1]))</code> but also ...
<p>One thing you need to understand, in python in general, is that, semantically, <code>__contains__</code> is based on <code>__eq__</code>, i.e. it looks for an element which satisfies the <code>==</code> predicate. (Of course one can override the <code>__contains__</code> operator to do other things, but that's a dif...
python|numpy
2
12,411
12,555,323
How to add a new column to an existing DataFrame?
<p>I have the following indexed DataFrame with named columns and rows not- continuous numbers:</p> <pre><code> a b c d 2 0.671399 0.101208 -0.181532 0.241273 3 0.446172 -0.243316 0.051767 1.577318 5 0.614758 0.075793 -0.451460 -0.012493 </code></pre> <p>I would like to add a n...
<p><strong>Edit 2017</strong></p> <p>As indicated in the comments and by @Alexander, currently the best method to add the values of a Series as a new column of a DataFrame could be using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="noreferrer"><strong><code>assi...
python|pandas|dataframe|chained-assignment
1,277
12,412
71,938,710
Extract elements from tensorflow dataset
<p>I have a tensorflow dataset containing all my data and labels. The first 20 elements are extracted into another dataset using following code:</p> <pre><code>train_dataset = big_dataset.take(20) </code></pre> <p>But how do i extract for example the last 20 elements from big_dataset into a new dataset?</p> <p>Thanks i...
<p>Try using <code>skip</code>. For example, suppose you have 120 data samples and a batch_size of 1 and you have not shuffled your data, then you can try something like the following:</p> <pre><code>train_dataset = big_dataset.skip(100).take(20) </code></pre> <p>For your specific dataset, try:</p> <pre><code>import te...
python|tensorflow|keras|tensorflow2.0|tf.keras
0
12,413
71,833,955
I need help working with pandas dataframe
<p>I have a big dataframe of items which is simplified as below. I am looking for good way to find the the item(A, B, C) in each row which is repeated more than or equal to 2 times.<br /> for example in row1 it is A and in row2 result is B.</p> <p>simplified df:</p> <pre><code>df = pd.DataFrame({'C1':['A','B','A','A','...
<p>Like mozway suggested, we don't know what will be your output. I will assume you need a list.</p> <p>You can try something like this.</p> <pre><code>import pandas as pd from collections import Counter holder = [] for index in range(len(df)): temp = Counter(df.iloc[index,:].values) holder.append(','.join([k...
python|pandas|pivot-table
0
12,414
72,113,963
Keras model.fit() runs faster on GPU when the CPU is loaded with a heavy multiprocessing script
<p>I wasn't expecting this to happen. The relevant code pieces are:</p> <pre><code>import os import tensorflow as tf os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices' ... csv_logger = CSVLogger(out_dir + 'log.csv', append = True, separator = '|') for epoch in range(epochs): np_i...
<p>After more research, empirical results show that limiting CPU parallelism indeed accelerates my model.fit().</p> <p>First, I've found:</p> <pre><code>config = tf.compat.v1.ConfigProto(intra_op_parallelism_threads = 4, inter_op_parallelism_threads = 1, allow_soft_place...
tensorflow|keras|parallel-processing
0
12,415
72,018,721
Pandas select rows by multiple conditions on columns
<p>I would like to reduce my code. So instead of 2 lines I would like to select rows by 3 conditions on 2 columns. My DataFrame contains Country's population between 2000 and 2018 by granularity (Total, Female, Male, Urban, Rural)</p> <pre><code> Zone Granularity Year Value 0 Afghanistan Total 2000...
<p>Very likely, you're using the wrong type for the year. I imagine these are integers.</p> <p>You should try:</p> <pre><code>df.loc[(df['Granularity'].isin(['Total', 'Urban'])) &amp; df['Year'].eq(2017)] </code></pre> <p>output (for the Year 2018 as 2017 is missing from the provided data):</p> <pre><code> Zo...
python|pandas|dataframe
2
12,416
16,839,840
Numpy/Scipy Sparse vs dense multiplication
<p>There appears to be some discrepancy between the scipy sparse matrix types and the normal numpy matrix type</p> <pre><code>import scipy.sparse as sp A = sp.dia_matrix(tri(3,4)) vec = array([1,2,3,4]) print A * vec #array([ 1., 3., 6.]) print A * (mat(vec).T) #matrix([[ 1.], ...
<p>In the <code>spmatrix</code> class (which you can check in scipy/sparse/base.py) the <code>__mul__()</code> there is a set of "ifs" that can answer your question:</p> <pre><code>class spmatrix(object): ... def __mul__(self, other): ... M,N = self.shape if other.__class__ is np.ndarra...
python|numpy|scipy|sparse-matrix|matrix-multiplication
3
12,417
18,879,272
Why does sum() operation on numpy masked_array change fill value to 1e20?
<p>Is this a feature or a bug? Can someone explain to me this behavior of a numpy masked_array? It seems to change the fill_value after applying the sum operation, which is confusing if you intend to use the filled result.</p> <pre><code>data=ones((5,5)) m=zeros((5,5),dtype=bool) """Mask out row 3""" m[3,:]=True arr=...
<p>The array returned by <code>arr.sum</code> is a new array which does not inherit the fill_value of <code>arr</code> (though I agree that might be a nice improvement to <code>np.ma</code>). As a workaround, you could use</p> <pre><code>In [18]: farr.filled(arr.fill_value) Out[18]: array([ 5., 5., 5., nan, 5....
python|numpy
2
12,418
22,268,509
fitting an image with 2D equation in python
<p>I have an image and I want to fit it to 2D equation in order to extract nx and ny parameters. First I defined 2D function and residuals from fit then I read the image file and then I tried to fit it using leastsq method, this is my code: </p> <pre><code>#!/usr/bin/python import pyfits import numpy as np import...
<p>Simply replace <code>residuals()</code> with the following should solve your problem:</p> <pre><code>def residuals(p,y,nx,ny): nx,ny = p err = y-fun(nx,ny) return err.flatten() </code></pre> <p>Basically I suspect the function call of <code>residuals(p0, meas, nx, ny)</code> would return a <code>2d arr...
python|numpy|matplotlib|scipy|pyfits
1
12,419
8,794,610
Neighbourhood of Scipy Labels
<p>I've got an array of objects labeled with <code>scipy.ndimage.measurements.label</code> called <code>Labels</code>. I've got other array <code>Data</code> containing stuff related to <code>Labels</code>. How can I make a third array <code>Neighbourhoods</code> which could serve to map <b>the nearest label to <i>x,y<...
<p>As suggested by David Zaslavsky, this is the job for a voroni diagram. Here is a numpy implementation: <a href="http://blancosilva.wordpress.com/2010/12/15/image-processing-with-numpy-scipy-and-matplotlibs-in-sage/" rel="nofollow">http://blancosilva.wordpress.com/2010/12/15/image-processing-with-numpy-scipy-and-matp...
python|numpy|scipy
2
12,420
55,169,540
Pandas Plot: scatter plot with index
<p>I am trying to create a scatter plot from pandas dataframe, and I dont want to use matplotlib plt for it. Following is the script </p> <pre><code>df: group people value 1 5 100 2 2 90 1 10 80 2 20 40 1 7 10 </code></pre> <p>I want to create a scatter plot with index on x ...
<p>You can try and use:</p> <pre><code>df.reset_index().plot.scatter(x = 'index', y = 'value') </code></pre> <p><a href="https://i.stack.imgur.com/noyod.png" rel="noreferrer"><img src="https://i.stack.imgur.com/noyod.png" alt="enter image description here"></a></p>
python|pandas|matplotlib|plot
12
12,421
55,316,502
What is the best way to fill each row of a column based on a condition of another cell, within the same row?
<p>I am attempting to fill a dataframe column 'Classification' with strings which indicate whether the value falls within the 200 lowest, or 200 highest values of a column titled, 'Valence_mean'.</p> <p>So, if a value of a cell within the 'Valence_mean' column is in the 200 lowest values of the column's values, the la...
<pre><code>df.loc[df.nsmallest(200,'Valence_mean').index.values,["Classification"]]="Low_valence" </code></pre> <p>You can get index values and change the values</p>
python|pandas|dataframe
0
12,422
55,398,498
Get a new column (consensus of element in others) with pandas
<p>I need some help using pandas data frames. Here is the data frame:</p> <pre><code>group col1 col2 name 1 dog 40 canidae 1 dog 40 canidae 1 dog 40 canidae 1 dog 40 canidae 1 dog 40 1 dog 40 canidae 1 dog 40 ...
<p>You'll need to define your own function. Make sure to replace the empty strings with <code>NaN</code> so they are never considered. <code>transform</code> can get tricky with calculations based on multiple columns, so instead groupby and map the result back to the original.</p> <pre><code>import numpy as np def my...
python|python-3.x|pandas|pandas-groupby
4
12,423
55,326,761
Iterator protocol within numpy
<p>Is there a way to work with iterators instead of (for example) <code>numpy.ndarray</code> in numpy? </p> <p>For example, imagine I have a 2D-array and I want to know if there is a row that only contain even numbers: </p> <pre class="lang-py prettyprint-override"><code>import numpy as np x = np.array([[1, 2], [2, ...
<p>The number of temporary arrays may be more than you realize:</p> <pre><code>In [224]: x = np.array([[1, 2], [2, 4], [3, 6]]) In [225]: x % 2 Out[225]: array([[1, 0], [0, 0], [1, 0]]) In [226]: _ == 0 ...
python|numpy|iterator
1
12,424
56,813,590
Finding where each unique subarray occurs
<p><strong>Situation:</strong></p> <p>I'm filling a narray of shape (2N, 2N), where N is close to 8000, call it A, with values I get from a function by using nested for loops to call a function that takes as argument subarrays of shape (2,) from the last dimension of an array of shape (N,N,2), call it B. </p> <p>This...
<p>Vectoring is often better. a slight rearrangement of your function facilitate the job :</p> <pre><code>import numpy as np def average_lat_pos(a,b,x,y): # all arguments are scalars return a*x+2*b*y # as example n=1000 B=np.random.rand(n,n,2) def loops(): A=np.empty((2*n,2*n)) for i in ...
python|arrays|numpy|vectorization
0
12,425
56,598,674
How to install older version of pytorch
<p>Following this <a href="https://pytorch.org/get-started/previous-versions/#via-pip" rel="noreferrer">https://pytorch.org/get-started/previous-versions/#via-pip</a></p> <pre><code>pip install torch==0.2.0_4 -f https://download.pytorch.org/whl/cpu/stable Collecting torch==0.2.0_4 Could not find a version that satis...
<pre><code>pip install torch== Collecting torch== </code></pre> <blockquote> <p>ERROR: Could not find a version that satisfies the requirement torch== (from versions: 0.1.2, 0.1.2.post1, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0) ERROR: No matching distribution found for torch==</p> </blockquote> <p>This means...
python|pip|pytorch
5
12,426
25,857,555
Trim Pandas DataFrame based on values in list
<p>I'm trying to trim a DataFrame based on an input list, but I need to check if the items in the list are in some of the frame's columns. </p> <p>(data below is random)</p> <p>The frame I'd like to trim looks like this:</p> <pre><code> UID S1 S2 ElementHID n1 n2 n3 n4 0 88.340153 -88....
<p>you can do something like:</p> <pre><code>&gt;&gt;&gt; i = element_frame[['n1', 'n2', 'n3', 'n4']].isin(node_list).any(axis=1) </code></pre> <p>and then, <code>i</code> would be the boolean indexer:</p> <pre><code>&gt;&gt;&gt; element_frame[i] </code></pre>
python|pandas
2
12,427
26,343,815
Converting non-numeric integers in column that also contains strings
<p>I have a dataframe that looks like the junk column below:</p> <pre><code>d = {'Junk Column' : ['1', '2', '3', '4', '5', '6', '7', 'J', 'K'], 'Good Column' : [1, 2, 3, 4, 5, 6, 7, 'J', 'K']} df = pd.DataFrame(d) Good Column Junk Column 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6...
<p>This may be faster:</p> <pre><code>&gt;&gt;&gt; df good junk 0 1 1.25 # a float 1 2 2 # already an int 2 3 +3 3 4 -4 # signed 4 5 5 # leading/trailing space 5 6 6 6 7 7 7 J J 3 8 K K5 &gt;&gt;&gt; df['junk'].values array([1....
python|pandas|dataframe
0
12,428
26,034,805
Condition on numpy arrays
<p>I have two arrays with the same number of elements</p> <pre><code>X = [1,2,3,4,5,6,7,8,9] Y = [10,4,3,7,7,3,1,8,98] </code></pre> <p>I would like to keep the elements of X and Y such as <code>2&lt;X&lt;7</code>. How can I do?</p> <p>Ok it works well with </p> <pre><code> Y = Y[np.logical_and(X&gt;2, X&lt;5)] X ...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow"><code>numpy.logical_and</code></a>:</p> <pre><code>&gt;&gt;&gt; X = np.array([1,2,3,4,5,6,7,8,9]) &gt;&gt;&gt; X[np.logical_and(X&gt;2, X&lt;7)] array([3, 4, 5, 6]) </code></pre>
python|arrays|numpy
2
12,429
66,958,951
Convert DataFrame to a multi polygon DataFrame, multiple data point - python
<p>I have a DataFrame as below, I want to convert data to a multi polygon DataFrame, because I want to plot each multi polygon on a map.</p> <p>I know how to convert if I have two data point, but with 6 data point, I don't know how to convert it. can anyone help me please.</p> <pre><code> geometry = [Point(xy) for xy ...
<p>Try this, assuming the 'lan' is latitude.</p> <pre><code>import geopandas as gpd from shapely.geometry import Polygon import numpy as np import pandas as pd import folium # .... def addpolygeom(row): row_array = np.array(row) # split dataframe row to a list of tuples (lat, lon) coords = [tuple(i)[::-1]...
python|dataframe|polygon|geopandas
1
12,430
67,078,196
Score function from RandomizedSearchCV gives different results on the same data set
<p>I'm running a RandomizedSearchCV using several pipelines (scaling, imputing, one-hot-encoding) to perform hyperparameter optimization for a random forest. I fit the model on my training data set and have been then using the <code>model.score()</code> function to assess its performance. Strangely, every time I run th...
<p>After some digging I discovered the part of the code that was responsible for the strange behaviour I was observing. It turns out the argument <code>sample_posterior = True</code> in the IterativeImputer was causing the issues. From <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeI...
python|pandas
0
12,431
66,874,237
Having trouble making update in gradient descent implementation?
<p>Hi I am working on implementing gradient descent with backtracking line search. However when I try to update f(x0) the value doesn't change. Could it be something going on with the lambda expression, I am not too familiar with them?</p> <pre><code>import numpy as np import math alpha = 0.1 beta = 0.6 f = lambda x: ...
<p><strong>Update for new code</strong></p> <p>OK, your numbers now change too much!</p> <p>When writing these routines stepping through the code with a debugger is really useful to check that the code is doing what you want. In this case you'll see that on the second pass through the loop <code>x0 = [-1.32e+170, 3.96e...
python|numpy|convex-optimization
1
12,432
66,910,391
Normalization python
<p>I'm trying to normalize a numpy array but I'm not getting the expected values( from 0 to 1).</p> <p>Here how I approached the problem:</p> <p>Suppose <code>a</code> is a numpy array</p> <pre><code>result = a - np.mean(a) / np.sqrt(np.sum((a-np.mean(a) ** 2) / (len(a)-1) </code></pre>
<p>Normalization doesn't mean you get values from 0 to 1, it just adjusts scales to comparable magnitudes and/or removes bias. If you want to normalize to the 0-1 range you have to subtract <code>np.min(a)</code> and divide by <code>np.max(a)-np.min(a)</code>.</p> <pre><code>a = (a - np.min(a))/(np.max(a)-np.min(a)) </...
python|numpy
2
12,433
66,829,282
how to clip pandas for a multiple column in a data frame
<p>Here is the df:</p> <pre><code>{'Type 1': {1: 123.0, 2: 123.0, 3: 123.0, 4: 123.0, 5: 123.0, 6: 45.0, 7: 45.0, 8: 45.0, 9: 45.0, 10: 9.5, 11: 9.5, 12: 9.5, 13: 2.34, 14: 2.34, 15: 2.34}, 'Type 2': {1: 0, 2: 0, 3: -90, 4: -90, 5: -90, 6: -90, 7: -90, 8: -270, 9: -270, 10...
<p>From <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.clip.html" rel="nofollow noreferrer">documentation</a>, <code>lower</code> and <code>upper</code> must be <code>float</code> or <code>array-like</code>, not <code>Series</code>.</p> <p>You could do</p> <pre><code>lower_limit = [3,-90,0,0,0,1...
python|pandas
3
12,434
47,500,081
Appending a new row to an existing dataframe
<p>I am trying to insert a new record to a data frame and am getting this error - <code>DataFrame constructor not Properly called</code>.</p> <p>This is my code,</p> <pre><code>import pandas as pd #defining the dataframe dfHeader = { 'Name': [], 'Daily': [],'Weekly': [],'Monthly': [],'Yearly': [], 'Area...
<p>If you need to add a single row:</p> <pre><code>In [136]: dFrame.loc[len(dFrame)] = row In [137]: dFrame Out[137]: Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly 0 NA NA NA NA NA NA NA NA NA </code></pre> <p>NOTE: usually it's much better, faster, less mem...
python|pandas|dataframe
1
12,435
47,152,923
assign value to new column [Python pandas]
<p>I have a scenario where I am running two functions in a script:</p> <p>test.py :</p> <pre><code>def func1(): df1=pd.read_csv('test1.csv') val1=df['col1'].mean().round(2) return va11 def func2(): df2=pd.read_csv('test2.csv') val2=df['col1'].mean().round(2) return val2 def func3(): data...
<p>You need pass variables as parameters in function <code>func3</code>, and if only difference in <code>func1</code> and <code>func2</code> is file name, create only one function with parameetr .</p> <p>Thanks for idea <a href="https://stackoverflow.com/questions/47152923/assign-value-to-new-column-python-pandas/4715...
python|python-2.7|python-3.x|pandas|csv
2
12,436
47,338,052
Nested range() in range() in Python
<p>Can you nested the range in range? Use variable in range? Because I would like to get some effect. To illustrate the problem I have the following pseudocode:</p> <pre><code>for i in range(str(2**i) for i in range(1,2)): print (str(i*0.01)) </code></pre> <p>At the exit I would like to receive:</p> <pre><code>0...
<p>For this specific task you'll want to nest them like this:</p> <pre><code>for i in range(1,3): for j in range(2**i): print(i * 0.01) </code></pre> <p>which will print what you want. What this is doing is taking a number <code>i</code> in <code>range(1,3) #[1,2]</code> and then print <code>i * 0.01</cod...
python|numpy
4
12,437
47,539,271
Multiple conditional selection using list of variables
<p>I'm cleaning up a data set and would like to filter it using a list of variables that satisfy a condition. Such as</p> <pre><code>import pandas as pd import numpy as np data = {"var1": [0,1,0,0,0], "var2": [0,0,0,0,0], "var3": [0,0,0,0,1], 'var4': [0,0,0,0,0], 'var5': [1,2,3,4,5] ...
<p><code>isin</code> +<code>any(1)</code></p> <pre><code>df[['var1','var2','var3','var4']].isin([1]).any(1) Out[538]: 0 False 1 True 2 False 3 False 4 True dtype: bool </code></pre>
python|pandas
1
12,438
68,195,301
DF - Sorting specific columns based on character code values
<p>I have below dataframe and I need to perform sort based on 6th, 3rd and 4th column values. sorting should be based on ASCII character code corresponding to the column values. &quot;&quot;ASCII Character code is Digits are the lowest value characters and followed by uppercase letter, followed by lowercase letters&quo...
<p>Unless I'm missing something this is as simple as using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer">.sort_values</a></p> <pre class="lang-py prettyprint-override"><code>df1.sort_values([&quot;6&quot;,&quot;3&quot;,&quot;4&quot;]) </...
python|pandas|dataframe|sorting
0
12,439
68,289,209
How to use constants in loss function?
<p>I know this is dumb, but I need the equivalent of <code>np.sqrt(2.0*np.pi)</code> in my loss function. How can I get it? Statements like this give error: 'float object has no attribute dtype':</p> <pre><code>pi = np.pi def myLoss(...): k = K.sqrt(2.0*pi) ... </code></pre> <p>Even <code>K.sqrt(2.0*3.14159)</co...
<p>Use it like this:</p> <pre><code>k = K.sqrt(tf.constant([2.0*np.pi])) </code></pre> <p>Since, it accepts an object which has dtype. One option is a Tensor.</p> <p>Another option is to not using keras backend, but using numpy:</p> <pre><code>k = np.sqrt(2.0*np.pi) </code></pre>
tensorflow|keras
0
12,440
68,415,512
Update array while inside for loop over arrays
<p>I have a Numpy array and can successfully update all its elements with one line:</p> <pre class="lang-py prettyprint-override"><code>array_1 = np.array([1, 2, 3, 4]) array_1 = array_1 / 10.0 print(array_1) # [0.1 0.2 0.3 0.4] -- Success! </code></pre> <p>However, when I have a list of Numpy arrays and iterate over ...
<p>You can make a shallow copy of the target array inside the for loop to edit the original.</p> <pre><code>for array in [array_1,array_2,array_3]: array[:] = array / 10.0 </code></pre> <p>EDIT With Explanation---</p> <p>In the for loop the control variable is its own object that deep copies the item being iterated...
python|numpy
2
12,441
68,119,256
Keras: Does model.predict() require normalized data if I train the model with normalized data?
<p>After completing model training using Keras I am trying to use Keras' <code>model.predict()</code> in order to test the model on novel inputs.</p> <p>When I trained the model, I normalized my training data with Scikit Learn's <code>MinMaxScaler()</code>.</p> <p>Do I need to normalize the data as well when using <cod...
<p>Yes. You need. Because your model has learned from data with a specific scale, so, it's better to convert your data to the same scale as your model works and then let it predict.</p> <p>For example, you may use the Scikitlearn library to normalize and standardize the data:</p> <pre><code>x_scaler = StandardScaler() ...
python|tensorflow|machine-learning|keras|scikit-learn
4
12,442
59,441,811
How to convert this forloop to pandas lambda function, to increase speed
<p>This forloop will take 3 days to complete. How can I increase the speed?</p> <pre><code>for i in range(df.shape[0]): df.loc[df['Creation date'] &gt;= pd.to_datetime(str(df['Original conf GI dte'].iloc[i])),'delivered'] += df['Sale order item'].iloc[i] </code></pre> <p>I think the forloop is enough to understan...
<p>Convert values to numpy arrays by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_numpy.html" rel="nofollow noreferrer"><code>Series.to_numpy</code></a>, compare them with broadcasting, match <code>order</code> values by <a href="https://docs.scipy.org/doc/numpy/reference/generate...
python|pandas
3
12,443
59,319,399
Can I check pandas dataframe index is end?
<p>I use while loop for show data in dataframe</p> <pre><code>while True: last_id = get_last_id() res = df.iloc[last_id + 1] </code></pre> <p>when last_id end of data and still use last_id + 1 it show error </p> <pre><code>IndexError: single positional indexer is out-of-bounds </code></pre> <p>Can I check i...
<p>Why not just remove <code>+1</code> from the last line:</p> <pre><code>while True: last_id = get_last_id() res = df.iloc[last_id] </code></pre>
python|python-3.x|pandas|dataframe
7
12,444
45,036,303
How to apply default and None operation names when constructing operations with Java Tensorflow API?
<p>Many tf operations have optional/default 'name' argument, but it seems there is no way to use the default value or avoid specifying it when constructing operations with Java API. So I have two questions:</p> <ol> <li>Is it possible to use default operation name when building it? If so, what should I pass to <code>o...
<p>By "many tf operations have optiona/default 'name' argument", I take it to mean that you're talking about the Python API for TensorFlow, where functions like <a href="https://www.tensorflow.org/api_docs/python/tf/add" rel="nofollow noreferrer"><code>tf.add</code></a> take a 'name' argument.</p> <p>The default in th...
java|tensorflow
1
12,445
44,937,860
Faster apply method in pandas
<p>I have a function that I'm trying to apply to a dataframe of locations. Specifically, I want to append a new column that contains the 10 closest sites to each site. The following seems to work, but it is excruciatingly slow. </p> <pre><code>def distance(first_lat, first_lon, second_lat, second_lon): return ((fi...
<p>Notice that your code has a time complexity of O(n^2): In this case, you're computing 30k*30k=900 million distances within an apply function that's in a for loop, i.e. pure Python.</p> <p>Vector operations in pandas are implemented in C, so you would get a relative speedup if you calculated all the distances in a s...
python|pandas
2
12,446
44,963,135
Index out of bounds / IndexError
<p>I am trying to move a kernel around an array of an image to create a gaussian filter. I am getting an IndexError, and Idk why. This is the code: error at line 34</p> <pre><code>import numpy as np import scipy from scipy import misc import matplotlib.pyplot as plt imagen_nueva = np.empty((1931, 1282)) imagen = sci...
<p>With some minor modifications to your code, such as fixing indentation and using an open source image i do not get any error. So it seems like an indentation errror.</p> <p>See working code below:</p> <pre><code>import numpy as np import scipy from scipy import misc import matplotlib.pyplot as plt imagen_nueva = ...
python|arrays|numpy|scipy|bounds
1
12,447
57,055,774
Pass Input to tensorflow lite model in Android
<p>I have created a neural network that take numerical data as input and saved it as tensorflow lite model using python. I am trying to pass input to the model in Android. Shape of ndarray is 1*3 </p> <p>Sample of the input in python is as follows</p> <pre><code>np.array([[-0.276786765 ,8.41897583008 ,-0.022201538...
<p>Assuming you're using <a href="https://www.tensorflow.org/lite/guide/inference#java" rel="nofollow noreferrer">TensorFlow Lite</a>, you can provide a 1x3 input using:</p> <pre><code>float[] innerInput = {-0.276786765 ,8.41897583008 ,-0.0222015380859 float[][] input = {innerInput}; interpreter.run(input, output); <...
python|tensorflow|neural-network|tensorflow-lite
0
12,448
57,064,375
Pandas str.replace method regex flag raises inconsistent exceptions
<p>When I use the <code>regex=[True|False]</code> flag in the <code>pd.Series.str.replace()</code> method, I get contradictory exceptions:</p> <ul> <li><code>repl</code> is a dictionary => it says <code>repl must be a string or callable</code></li> <li><code>repl</code> is a callable => it says <code>Cannot use a call...
<p>If you look at the documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>pandas.Series.str.replace</code></a> you will see that the <code>repl</code> argument can be a <em>string or callable</em>, but a <code>dict</code> ...
python|pandas
2
12,449
57,016,929
Sort trainable parameters in Keras
<p>When I have some trainable parameters, say <code>layer.trainable_weights</code>. I want to sort those weights before feed into other operations, is it possible for me to do that? Can I use something like </p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf p = layer.trainable_weights p = tf....
<p>Of course, you can do it. Since you have not stated clearly what these downstreaming operations are, it is more difficult to answer your question. </p> <p>If you only want to do something to monitor the training process, e.g. monitoring a custom metric to measure the cumulative distribution function of the weight m...
python|tensorflow|machine-learning|keras|deep-learning
0
12,450
56,913,326
how to create a function in python that gives elements of an array?
<p>I have an array. Let's say a=array([[10, 2, 13, 55]]) I want to create a function that gives me the 1st element for t=0, the second element for t=1... </p> <p>I have tried the following:</p> <pre><code>def a(t): return a[t] </code></pre>
<p>You can do it like this :</p> <pre class="lang-py prettyprint-override"><code>a=array([[10, 2, 13, 55]]) def get_value(t): return a[t] get_value(0) #results [10, 2, 13, 55] </code></pre> <p>Since your example data is 2D , if we want to access each of them we must pass 2 numbers as index.</p> <pre class="la...
python|arrays|function|numpy
1
12,451
56,915,156
add a column based on the values of another column of dataframe in pandas
<p>this is my dataframe:</p> <pre><code>df = pd.DataFrame({'symbol': ['msft', 'amd', 'bac', 'citi'], 'close': [100, 30, 70, 80]}) </code></pre> <p>I want to add another column called <code>sector</code> that checks the values of <code>symbol</code> and add the values that I want (<code>tech</code> for <code>amd</code...
<p>In case the sector-symbol relation is a straightforward lookup, you may use something like:</p> <pre class="lang-py prettyprint-override"><code>symbol_sector = { 'amd': 'tech', 'msft': 'tech', 'bac': 'bank', 'citi': 'bank' } df['sector'] = df['symbol'].map(symbol_sector) </code></pre> <p>If your r...
python|pandas
3
12,452
45,952,729
Can we create a jumbled table using pandas dataframe?
<p>Tables are usually having m rows and n columns. But can we create jumbled table in python ?</p> <p>Like:</p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>R programming language have a functionality which automatically filled the blank or uninitialized cell with 'NA'. For example, If we make above table in ...
<p>Yes, pandas does the same thing. For instance, here's an example of concatenating two dataframes with different lengths column-wise:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({"A":[1,2,3],"B":[2,65,4]}) &gt;&gt;&gt; df A B 0 1 2 1 2 65 2 3 4 &gt;&gt;&gt; df1 = pd....
r|python-3.x|pandas|dataframe
2
12,453
45,799,550
Pandas Row Date Conditional Filter Prior to Groupby - MAXIFS/MINIFS
<p>I am trying to do MAXIFS style calculations in Pandas</p> <p>I am trying to add a column containing the next (if exists) &amp; last (if exists) flagged date for each unique ID</p> <p>Sample Table: (Trying to get the Next Flag &amp; Last Flag Columns)</p> <p>Edit: To form a more generic case, what if you wanted to...
<p>Try this ? I break down the steps , Assuming you already <code>sort_values</code> by column <code>Id</code> and <code>Date</code></p> <pre><code>df['Next Flag']=np.nan df['Last Flag']=np.nan df.loc[(df.Flag==1).shift().fillna(False),'Next Flag']=df.Date.shift() df.loc[(df.Flag==1).fillna(False),'Last Flag']=df.Date...
python|pandas|pandas-groupby
1
12,454
45,831,857
Transforming a CSV from wide to long format
<p>I have a csv like this:</p> <pre><code>col1,col2,col2_val,col3,col3_val A,1,3,5,6 B,2,3,4,5 </code></pre> <p>and i want to transfer this csv like this :</p> <pre><code>col1,col6,col7,col8 A,Col2,1,3 A,col3,5,6 </code></pre> <p>there are col3 and col3_val so i want to keep col3 in col6 and values of col3 in col7 ...
<p>I think what you're looking for is <code>df.melt</code> and <code>df.groupby</code>:</p> <pre><code>In [63]: df.rename(columns=lambda x: x.strip('_val')).melt('col1')\ .groupby(['col1', 'variable'], as_index=False)['value'].apply(lambda x: pd.Series(x.values))\ .add_prefix('value')\ ...
python|pandas|csv|dataframe
2
12,455
11,691,981
Matlab VS Python - eig(A,B) VS sc.linalg.eig(A,B)
<p>I have the following matrices sigma and sigmad:</p> <p>sigma:</p> <pre><code> 1.9958 0.7250 0.7250 1.3167 </code></pre> <p>sigmad:</p> <pre><code> 4.8889 1.1944 1.1944 4.2361 </code></pre> <p>If I try to solve the generalized eigenvalue problem in python I obtain:</p> <pre><code> d,V =...
<p>Any (nonzero) scalar multiple of an eigenvector will also be an eigenvector; only the direction is meaningful, not the overall normalization. Different routines use different conventions -- often you'll see the magnitude set to 1, or the maximum value set to 1 or -1 -- and some routines don't even bother being inte...
python|matlab|numpy|scipy|eigenvalue
11
12,456
28,726,839
Removing rows below first line that meets threshold in pandas dataframe
<p>I have a df that looks like:</p> <pre><code>import pandas as pd import numpy as np d = {'Hours':np.arange(12, 97, 12), 'Average':np.random.random(8), 'Count':[500, 250, 125, 75, 60, 25, 5, 15]} df = pd.DataFrame(d) </code></pre> <p>This df has a decrease number of cases for each row. After the count drop...
<p>We can use the index generated from the boolean index and slice the df using <code>iloc</code>:</p> <pre><code>In [58]: df.iloc[:df[df.Count &lt; 10].index[0]] Out[58]: Average Count Hours 0 0.183016 500 12 1 0.046221 250 24 2 0.687945 125 36 3 0.387634 75 48 4 0.167491 ...
python|python-2.7|pandas
2
12,457
50,841,239
How to separate a list item in to separate variables
<p>I'm working on a project for web scraping.</p> <p>I run into an issue where I run a for loop to iterate through a list but it brings it back as one.</p> <p>My aim is to separate each item inside the list and save it as a variable displaying it in a data frame, however, I'm faced with a block of text instead.</p> ...
<p>i think what would do the job is</p> <pre><code>df1 = df.Specs.str.split(pat='\n', expand=True) df1 = df1.replace('',np.nan) df1 = df1.dropna(axis=1, how='all') df1.columns = ['Spec_' + str(x) for x in list(df1)] df1 Spec_1 Spec_2 Spec_3 Spec_4 Spec_5 Spec_6 Spec_7 0 2008 (08 reg) Coupe ...
list|pandas|web-scraping|python-requests
1
12,458
20,633,506
How to solve the Pandas issue related to Series.fillna()?
<p>I just upgrade from Pandas 0.11 to 0.13.0rc1. The upgration caused one error related to Series.fillna().</p> <pre><code>&gt;&gt;&gt; df sales net_pft STK_ID RPT_Date 600809 20060331 5.8951 1.1241 20060630 8.3031 1.5464 20060930 11.9084 2.2990 200...
<p>There was a recent discussion on this, and it is fixed in pandas master: <a href="https://github.com/pydata/pandas/issues/5703" rel="nofollow">https://github.com/pydata/pandas/issues/5703</a> (after the release of 0.13rc1, so it will be fixed in final 0.13).</p> <p>Note: the behaviour changed! This was not supporte...
python|pandas
3
12,459
33,110,533
When I try to drop a single row in a pandas dataframe with datetimeindex, it shifts the index
<p>I have a dataframe with a datetimeindex index. When i try and drop a single row by its index value, the number of rows become N-1 correctly, but the times in the index shift. In fact, a large chunk of rows is chopped from the start, and then a chunk of rows with Nan values is added to the end. The size of this 'c...
<p>You should indicate you are using 0.17.0.</p> <pre><code>In [13]: import psycopg2 In [14]: df = DataFrame(np.arange(10),index=pd.date_range('20130101 09:00:00',periods=10,tz=psycopg2.tz.FixedOffsetTimezone(offset=-480, name=None),freq='H'),columns=['value']) In [15]: df Out[15]: value ...
python|pandas|datetimeindex
1
12,460
66,377,901
Keras model ValueError: Can not squeeze dim[1], expected a dimension of 1, got 90
<p>My current model is:</p> <pre><code># from tensorflow.keras.layers import InputLayer model_training = Sequential() # input_layer = keras.Input(shape=(300,1)) model_training.add(InputLayer(input_shape=(300,1))) model_training.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='tanh')) model_training.add...
<p>Squeeze your labels before training:</p> <pre class="lang-py prettyprint-override"><code>train_labels = tf.squeeze(train_labels, axis=-1) </code></pre> <p>It seems like the shape of your labels is the problem. The model will output a shape of <code>(batch, 90)</code>, but you are providing <code>(batch, 90, 1)</code...
python|tensorflow|keras
2
12,461
66,342,074
Calculate date difference of dataframe groups
<p>I have a dataframe where I need to calculate the length of time (in years) between dates of groups. For example, I want the difference between the <em>first</em> time a <code>Name</code>-<code>ID</code> group appeared (identified by <code>%_chng=New</code>), and the date in the <code>Date</code> column.</p> <pre><co...
<p>Let us do <code>cumsum</code> create the additional <code>groupby</code> key then do <code>transform</code></p> <pre><code>df.Date = pd.to_datetime(df.Date) s = df['%_chng'].eq('New').iloc[::-1].cumsum() datediff = df.groupby([df['Name'],df['ID'],s])['Date'].transform('last') df['date_length'] = (df['Date'] - datedi...
python|pandas
1
12,462
66,555,744
ValueError: Cannot assign to variable conv1_conv/kernel:0 due to variable shape (7, 7, 1, 64) and value shape (64, 3, 7, 7) are incompatible
<p>I am facing an issue using Resnet, Since i am new to this model it is a bit hard to find what might have gone wrong. Initially i tried to use the input shape as (10, 224, 224, 1) but this works only for 2d cnn or 3d cnn models but not for Resnet. Is there a workaround or i have to use only CNN models?</p> <p>Please ...
<p>I got this error when I was using python3.8 with tensorflow. When I changed back to python3.6 with tensorflow, it works well with no errors.</p>
python|tensorflow|deep-learning|neural-network
0
12,463
16,246,643
Adding records to a numpy record array
<p>Let's say I define a record array</p> <pre><code>&gt;&gt;&gt; y=np.zeros(4,dtype=('a4,int32,float64')) </code></pre> <p>and then I proceed to fill up the 4 records available. Now I get more data, something like</p> <pre><code>&gt;&gt;&gt; c=('a',7,'24.5') </code></pre> <p>and I want to add this record to <code>...
<p>You can use <code>numpy.append()</code>, but as you need to convert the new data into a record array also:</p> <pre><code>import numpy as np y = np.zeros(4,dtype=('a4,int32,float64')) y = np.append(y, np.array([("0",7,24.5)], dtype=y.dtype)) </code></pre> <p>Since ndarray can't dynamic change it's size, you need t...
python|numpy|concatenation|record
26
12,464
57,509,069
Convert models( ?weights ) downloaded using applications module to tflite
<p>I am trying to convert mobilenet model downloaded using applications module in tf.keras to tensorflow lite format. TensorFlow version I am using is 1.31. I don't know whether model is actually stored weights only or weights+architecture+optimizer_state. When I tried the conversion command :</p> <pre><code>from tens...
<p>How did you saved your model,maybe you have saved only weights not model and you are trying to call load model which is not present.</p> <p>If this is not the problem try to clear session.</p> <pre><code>from keras.backend import clear_session clear_session() </code></pre> <p>I convert the model in this way</p> ...
python|tensorflow|keras|tf.keras
0
12,465
57,717,961
converting the values in a text file and making new text file in python
<p>I have a text file like this example:</p> <p>example:</p> <pre><code>"class" "Name" "Access" "CF33456_12.RCC" "CF33457_05.RCC" "CF33458_04.RCC" "ff" "edi" "ff" "kju" 2444.91910958478 1669.55827263364 699.627215729572 "gg" "edi" "gg" "uhy" 2002.95278984564 369.565070720533 ...
<p>In your example the original dataframe (which has the structure of the input table) can be changed using this code:</p> <pre><code> df = pd.read_table("myfile.txt", index_col=0) import numpy as np df2 = df.iloc[:, [3:5]] df3 = np.array(df2) df4 = np.log2(df3) df.iloc[:, [3:5]] = df4 final...
python-3.x|pandas|file
0
12,466
57,519,243
access pyodbc object in dataframe
<p>Probably a naive question but any pointers would be appreciated. </p> <p>I am trying to connect to my database and then trying to put the data in the pandas dataframe. However I am not able to achieve the same. </p> <p>Here is the code that I am trying : </p> <pre><code>import pandas as pd import pyodbc server = ...
<p><code>df = pd.Dataframe(cursor.fetchall(),columns=resoverall.keys())</code></p>
python|pandas|pyodbc
0
12,467
24,259,988
Change formatting on datetime ticks when plotting daily mean with Pandas/matplotlib
<p>I'm calculating the daily mean with the standard deviation as a bar plot. My dataframe looks like this:</p> <pre><code> Ozone 2014-06-10 41.958586 2014-06-11 32.747222 2014-06-12 35.781250 2014-06-13 28.623264 2014-06-14 31.160764 2014-06-15 30.494444 2014-06-16 35.666667 [7 rows x 1 columns]...
<p>One possiblity is that as Pandas/Matplotlib is taking the dates as <code>datetime</code> values if you convert them to strings then you can control the format by using the <code>datetime.strftime</code> method.</p>
python|matplotlib|plot|pandas
2
12,468
72,907,288
Pandas str.extract() a number that ends in a letter
<p>I have a pandas column like below:</p> <pre><code> df['description'] 0. PRAIRIE HIGHLANDS SIXTH PLAT Lt: 156 PIN# DP73770000 0156 312 ABC 1. PRAIRIE VILLAGE PIN# OP55000034 0020A Rmrk: PT OF 2. Sub: HOLLY GREEN Lt: 14 Bl: 1 PIN# DP34500001 0D14 3. FAIRWAY PIN# GP20000006 0029 Rmrk: W </code></pre> <...
<p>I would use <code>str.extract</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;PIN&quot;] = df[&quot;description&quot;].str.extract(r'PIN#((?: [A-Z0-9]*[0-9][A-Z0-9]*)*)') </code></pre> <p>Here is a link to a running regex <a href="https://regex101.com/r/Ep2R8h/1" rel="nofollow norefer...
python|regex|pandas
1
12,469
72,946,256
How to concatenate two csv files horizontally to one dataframe?
<p>Suppose I have two csv files / pandas data_frames</p> <pre><code>file1.csv -&gt; file A --------- 0 K0 E1 1 K0 E2 2 K0 E3 3 K1 W1 4 K2 W2 file2.csv -&gt; file B -------- 0 K0 E3 1 K0 W3 2 K1 E4 3 K1 W4 4 K3 W5 </code></pre> <p>How to merge/concatenate them to get a resul...
<p>You can try 'np.concatenate((a,b), axis=0)'</p>
python|pandas|dataframe|csv
0
12,470
73,039,047
List param into sheet_name pandas read_execel()
<p>Im trying to send a list in sheet_name for access more then one sheet from .csv file and when i print df &quot;<code>df = pd.read_excel( &quot;https://www.football-data.co.uk/mmz4281/2122/all-euro-data-2021-2022.xlsx?raw=true&quot;, sheet_name=liga)</code>&quot; works, he print me two sheets but in next line he said...
<p><code>pd.read_excel</code> returns a dictionary like</p> <pre class="lang-py prettyprint-override"><code>{'D1': dataframe1, 'D2': dataframe2} </code></pre> <p>You need get the dataframe with dictionary key like</p> <pre><code> d = pd.read_excel( &quot;https://www.football-data.co.uk/mmz4281/2122/all-euro-...
python|pandas
0
12,471
70,391,141
Change certain categorical variables to a unified entry
<p>Let's say I have have a dataframe with a column called animals. The entries look as followed:</p> <pre><code>'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'E', 'F', 'G', 'H', 'I'. </code></pre> <p>I want to change the entries 'E', 'F', 'G', 'H' and 'I' to another unified entry called 'D'. What is the best way to transform...
<p>You can create a <code>list</code> of the entries you want to change, and then you can assign 'D' for them using <code>loc</code> to spot them, and <code>isin</code> to evalute if your condition is satisfied:</p> <pre><code>li = ['E','F','G','H','I'] df.loc[df.animals.isin(li), 'animals'] = 'D' </code></pre> <p>An a...
python|pandas|dataframe|categorical-data
2
12,472
70,612,777
Dataclass and Callable Initialization Problem via Classmethods
<p>I found this weird behaviour where I don't know if I am the problem or if this is a python / dataclass / callable bug.</p> <p>Here is a minimal working example</p> <pre><code>from dataclasses import dataclass from typing import Callable import numpy as np def my_dummy_callable(my_array, my_bool): return 1.0 ...
<p>The <code>@dataclass</code> decorator by default supplies an <code>__init__()</code> method to a class. This method turns type annotated class variables into attributes of instances of the class. This mechanism is used in the case of the class <code>MySecondDataClassDummy</code>. In effect, every instance of this cl...
python|python-3.x|numpy|callable|python-dataclasses
1
12,473
70,539,124
Alternatively assign values to two column
<p>I have a dataset that looks as follows</p> <pre><code> Datetime Message 0 2021-12-20 09:50:08.819 Current sidewing pressure: 3362 1 2021-12-20 09:50:08.820 Current sidewing pressure: 3303 2 2021-12-20 09:50:08.839 Current sidewing pressure: 3398 3 2021-12-20 09:50:08.839 Current sidewin...
<p>You can use <code>iloc[::2]</code> to extract every other value (<code>::2</code> for even indices values, and <code>1::2</code> for odd indices values) and assign to a column:</p> <pre><code>vals = df.Message.str.extract('(\d+)$') df['Right'] = vals.iloc[::2] df['Left'] = vals.iloc[1::2] df Datet...
python|pandas|dataframe
2
12,474
42,627,091
pandas parse csv with left and right quote chars
<p>I am trying to read a file in pandas which is structured as follows</p> <pre><code>&lt;first&gt;$$&gt;&lt;$$&lt;second&gt;$$&gt;&lt;$$&lt;first&gt;$$&gt; &lt;foo&gt;$$&gt;&lt;$$&lt;bar&gt;$$&gt;&lt;$$&lt;baz&gt;$$&gt; </code></pre> <p>using <code>pd.read_csv('myflie.csv', encoding='utf8', sep='$$&gt;&lt;$$', decim...
<p>You need escape <code>$</code> by <code>\</code>, because it is read as regex (end of string):</p> <blockquote> <p>(separators > 1 char and different from '\s+' are interpreted as regex)</p> </blockquote> <pre><code>import pandas as pd from pandas.compat import StringIO temp=u"""&lt;first&gt;$$&gt;&lt;$$&lt;se...
python|csv|parsing|pandas
3
12,475
42,983,799
What is wrong with this pandas code?
<pre><code>import pandas as pd s1 = pd.Series([1, 2, 3]) s2 = pd.Series([4, 5, 6]) s1.append(s2) print(s1) </code></pre> <p>Such a simple thing but Its not appending. Out up is : 0 1 1 2 2 3 dtype: int64 It just prints s1. Its not appending? What silly mistake am I doing here?</p>
<p>Because <code>.append</code> returns a new series, it doesn't mutate in place (like <code>list.append</code>). Try:</p> <pre><code>import pandas as pd s1 = pd.Series([1, 2, 3]) s2 = pd.Series([4, 5, 6]) s3 = s1.append(s2) print(s3) </code></pre>
python|pandas|series
2
12,476
42,686,065
Iteratively subsetting pandas chunks with .duplicated() gives me empty arrays
<p>I am reading in a large csv in chunks with Pandas. I subset each chunk to see if there are duplicated timestamps:</p> <pre><code>for c in chunks: dups= c.duplicated(subset='Timestamp') dups= dups[dups==True] print(dups) </code></pre> <p>When I print dups, I get the following:</p> <pre><code>255 Tr...
<p>In your loop, the line <code>dups= dups[dups==True]</code> returns an empty <code>Series</code> if <code>dups</code> is all <code>False</code>. If you don't want to print it when it's empty you could include a check for <code>len(dups) &gt; 0</code>:</p> <pre><code>for c in chunks: dups= c.duplicated(subset='Ti...
python|pandas|bigdata
0
12,477
27,010,793
How to make this rounding function faster?
<p>I am trying to write a function to round values to the nearest valid odds in a list from here: <a href="https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Betfair+Price+Increments" rel="nofollow noreferrer">https://api.developer.betfair.com/services/webapps/docs/display/1sm...
<p>You can get a speed increase in numpy by creating a magnitude array and then doing the rounding all at the end with the magnitude array.</p> <pre><code>def nclosest_valid_odds_3( x ): magnitudes = np.empty_like(x) magnitudes[x &lt; 1] = np.nan magnitudes[(1 &lt;= x) &amp; (x &lt;= 2)] = 0.01 v = ...
python|multithreading|numpy|multiprocessing|numba
2
12,478
27,108,850
Tuples of closed continuous intervals
<p>Say I have the following list of numbers:</p> <pre><code>my_array = [0, 3, 4, 7, 8, 9, 10, 20, 21, 22, 70] </code></pre> <p>I would like to find every closed interval containing <strong>consecutive integers without gaps</strong> in this list. If for any number in the list there are multiple such intervals, we <str...
<p>I don't have a numpy install handy, but this is the approach that I would take. First handle the case of an empty array separately. Sort the array if it isn't already sorted and use <code>np.diff</code> to compute the differences.</p> <pre><code>0, 3, 4, 7, 8, 9, 10, 20, 21, 22, 70 3 1 3 1 1 1 10 1 1...
python|algorithm|numpy
3
12,479
25,113,682
Acces all off diagonal elements of boolean numpy matrix
<p>Suppose there is a diagonal matrix M:</p> <pre><code>#import numpy as np M = np.matrix(np.eye(5, dtype=bool)) </code></pre> <p>Does anybody know a simple way to access all off diagonal elements, meaning all elements that are <code>False</code>? In <code>R</code> I can simply do this by executing </p> <pre><code>...
<p>You need the bitwise not operator:</p> <pre><code>M[~M] </code></pre>
python|numpy|matrix
8
12,480
39,378,535
Changing data in a DataFrame column (Pandas) with a For loop
<p>I'm trying to take the data from "Mathscore" and convert the values into numerical values, all under "Mathscore."</p> <p>strong =1 Weak = 0</p> <p>I tried doing this via the function below using For loop but I can't get the code to run. Is the way I'm trying to assign data incorrect?</p> <p>Thanks! </p> <pre><c...
<p>you can <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow">categorize</a> your data:</p> <pre><code>In [23]: df['Mathscore'] = df.Mathscore.astype('category').cat.rename_categories(['1','0']) In [24]: df Out[24]: Id_Student Mathscore 0 1 1 1 2 ...
python|pandas|dataframe
3
12,481
39,128,145
Average of numpy array ignoring specified value
<p>I have a number of 1-dimensional numpy ndarrays containing the path length between a given node and all other nodes in a network for which I would like to calculate the average. The matter is complicated though by the fact that if no path exists between two nodes the algorithm returns a value of 2147483647 for that ...
<p>Why not using your usual numpy filtering for this?</p> <pre><code>m = my_array[my_array != 2147483647].mean() </code></pre> <p>By the way, if you really want speed, your whole algorithm description seems certainly naive and could be improved by a lot.</p> <p>Oh and I guess that you are calculating the mean becaus...
python|arrays|performance|numpy|graph-tool
5
12,482
39,357,882
Pandas DENSE RANK
<p>I'm dealing with pandas dataframe and have a frame like this:</p> <pre><code>Year Value 2012 10 2013 20 2013 25 2014 30 </code></pre> <p>I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:</p> <pre><code> Year Value Rank 2012 10 1 ...
<p>Use <code>pd.Series.rank</code> with <code>method='dense'</code></p> <pre><code>df['Rank'] = df.Year.rank(method='dense').astype(int) df </code></pre> <p><a href="https://i.stack.imgur.com/67n7I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/67n7I.png" alt="enter image description here"></a></p>
python|sql|pandas
21
12,483
39,376,770
Comparing 3d tensor and 4d tensor Tensorflow
<p>I have the following U-Net which I use to segment grayscale PNG images. </p> <pre><code>import cv2 import os from sklearn.utils import shuffle import tensorflow as tf import numpy as np OVERALLSIZE = int(float(input('Choose the number of images you want (&lt;5635) : '))) PATH = input('give absolute path to image'...
<p>stick a tf.newaxis into the tensor.</p> <pre><code>x = x[:,:, :, tf.newaxis] </code></pre> <p>or use tf.squeeze to get rid of the extra axis in y.</p> <pre><code>y = tf.squeeze(y, axis=-1) </code></pre>
python|tensorflow
0
12,484
29,334,205
PYTHON - Error while using numpy genfromtxt to import csv data with multiple data types
<p>I'm working on a kaggle competition to predict restaurant revenue based on multiple predictors. I'm a beginner user of Python, I would normally use Rapidminer for data analysis. I am using Python 3.4 on the Spyder 2.3 dev environment.</p> <p>I am using the below code to import the training csv file. </p> <pre><cod...
<p>[Solved].</p> <p>I just chucked numpy's genfromtext and opted to use read_csv from pandas since it gives the option to import text in 'utf-8' encoding. </p>
python|csv|python-3.x|numpy|data-mining
0
12,485
33,594,894
Adding scikit-learn (sklearn) prediction to pandas data frame
<p>I am trying to add a sklearn prediction to a pandas dataframe, so that I can make a thorough evaluation of the prediction. The relavant piece of code is the following:</p> <pre><code>clf = linear_model.LinearRegression() clf.fit(Xtrain,ytrain) ypred = pd.DataFrame({'pred_lin_regr': pd.Series(clf.predict(Xtest))}) <...
<p>You're correct with your second line, <code>df_total["pred_lin_regr"] = clf.predict(Xtest)</code> and it's more efficient.</p> <p>In that one you're taking the output of <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.predict...
python|numpy|pandas|scikit-learn
9
12,486
33,919,875
Interpolate irregular 3d data from a XYZ file to a regular grid
<p>I have a xyz file containing a lot of 3D coordinates like so:</p> <pre><code> 370373.771 6535261.431 2.908 370373.788 6535261.441 2.911 370373.787 6535261.442 2.909 370373.809 6535261.449 2.908 370373.810 6535261.439 2.909 370373.743 ...
<p>The <code>coord_z</code> argument passed in must also be an array:</p> <pre><code>grid = griddata(np.array(coord_xy), np.array(coord_z), (X, Y), method='nearest') </code></pre>
python|numpy|grid|interpolation
4
12,487
22,537,354
error when installing pandas package: no module named numpy
<p>I have a big solutions with multiple projects inside. I use <code>virtualenv</code> for that. So for one of my projects in solution I already install the stuff I need, including <code>numpy</code> and <code>pandas</code></p> <p>but when I I executing something like that:</p> <pre><code>cd ../project2 sudo python s...
<p>I recently had this error while trying to update Pandas from version 0.23.1 to 0.24.1. </p> <p>What solved my problem was to first update pip by executing:</p> <pre><code>python -m pip install --upgrade pip </code></pre> <p>And then updating the desired library.</p>
python|numpy|pandas
7
12,488
62,323,162
Get datetime64[ns] between two datetimes pandas
<p>I'm trying to extract the rows within a certain datetime. What am I doing wrong?</p> <pre><code>import pandas as pd df = pd.DataFrame({'year': [2015, 2016, 2017, 2016], 'month': [2, 3, 4, 6], 'day': [4, 5, 4, 3]}) df = pd.to_datetime(df) df = df.to_frame(name='test') start_d...
<p>There missing <code>()</code> becauase priority of operators:</p> <pre><code>print (df[(df['test'] &gt; start_date) &amp; (df['test'] &lt; end_date)]) </code></pre> <p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.betwee...
pandas|datetime
1
12,489
62,281,578
How to merge multiple pandas dataframes into one original dataframe in the most efficient way?
<p>How to merge 4 pandas dataframes into one original dataframe in the most efficient way? Below shows the original dataframe <code>df</code> whose 4 columns <code>CC1</code>, <code>CC2</code>, <code>CC3</code> and <code>CC4</code> need to be updated with the respective columns from <code>df1</code>, <code>df2</code>, ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> in list comprehension for create <code>MultiIndex</code> by <code>TD</code> and <code>PD</code> used for outer join by <a href="http://pandas.pydata.org/pandas-docs/stable/refe...
python|pandas|dataframe
2
12,490
62,203,593
Averaging rows from one pandas df to to another as mean (using two keys)
<p>I have two dataframes.</p> <p>DF1 looks like:</p> <p><a href="https://i.stack.imgur.com/SNCAH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SNCAH.png" alt="mock up of 4 column table, two id columns, two data columns representing averages"></a></p> <p>DF2 looks like:</p> <p><a href="https://i...
<p>Looks like you can try <code>groupby()</code> then <code>merge</code>:</p> <pre><code>df1.merge(df2.groupby(['ID_1','ID_2']).mean().add_suffix('_Mean'), on=['ID_1','ID_2']) </code></pre>
python|pandas|dataframe
0
12,491
62,369,319
what could be the reason for the importerror
<p>I am trying to train a model of CNN. <br> When I run the code, it returns following error:</p> <pre><code>Traceback (most recent call last): File "train_network.py", line 5, in &lt;module&gt; import matplotlib File "/home/kaustubhj/.virtualenvs/dl4cv/lib/python3.7/site-packages/matplotlib/__init__.py", line...
<p><strong>ImportError</strong> generally refers to an import library required for execution is not present within executing systems.</p> <p>Few possible cases to look for.</p> <ol> <li><p>In a general case, your system where py is running is missing this package.</p></li> <li><p>In Spark(general-purpose computing cl...
python|numpy|matplotlib
1
12,492
62,359,037
.eq() method is not giving same result as [ == ]
<p>I am having a hard time understanding why the results are not the same for following code.</p> <p>I am trying to find the accuracy of a model but the first item gives a result of tensor(66.), and second item gives a result of tensor(105).</p> <pre><code>(y_test[y_test==y_predicted_cls].sum(), y_predicted_cls.eq(y_...
<p>The statement <code>y_test[y_test==y_predicted_cls].sum()</code> gives the sum for the <code>y_test</code> list/array while, <code>y_predicted_cls.eq(y_test).sum()</code> gives the sum for <code>y_predicted_cls</code>, and in the first case, if both the arrays are same, it yields:</p> <pre><code>y_test[1].sum() </c...
python|pytorch
0
12,493
62,067,400
Understanding accumulated gradients in PyTorch
<p>I am trying to comprehend inner workings of the gradient accumulation in <code>PyTorch</code>. My question is somewhat related to these two:</p> <p><a href="https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch#">Why do we need to call zero_grad() in PyTorch?</a></p> <p><a href="...
<p>You are not actually accumulating gradients. Just leaving off <code>optimizer.zero_grad()</code> has no effect if you have a single <code>.backward()</code> call, as the gradients are already zero to begin with (technically <code>None</code> but they will be automatically initialised to zero).</p> <p>The only differ...
python|deep-learning|pytorch|gradient-descent
44
12,494
62,073,469
Array out of bounds by checking elements
<p>My for loop is always going out of bounds. It keeps checking whether the element is > 0. I tried plenty of restrictions, but none of them worked. Do you have any suggestions?</p> <pre><code>###Creation of the graph in a method def graph(self): ###Creation of the given array I added zero rows and columns because...
<p>To answer the question of why the restrictions don't work, let's examine one of them for example (substituing in the <code>d[0]</code> value, since the <code>d</code> list isn't actually helping us either with solving the problem or simplifying the code):</p> <pre><code>a[r-1, c] &gt; 0 and r &gt;= 0 </code></pre> ...
python|arrays|numpy
0
12,495
51,425,729
What is the best way to multiply arrays? in Python
<p>I have two arrays. </p> <pre><code>Array1 [[-0.23, 0.11], [0.29, -0.37]] Array2 ([5.28, 4.40]) </code></pre> <p>I want to do sum the multiplication of one array by the other</p> <p>Example </p> <ul> <li><p>sum(5.28 *-0.23 + 4.40 * 0.11) = ind1</p></li> <li><p>sum(5.28 *-0.29 + 4.40 * -0.37) = ind2</p></li>...
<p>Are you familiar with how to <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.creation.html" rel="nofollow noreferrer">create numpy arrays</a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html" rel="nofollow noreferrer">multiply</a> them?</p> <pre><code>numpy.matmul(Arr...
python|numpy
1
12,496
51,364,975
Datatype in NumPy
<p>I have come across the following statement in numpy:</p> <pre><code>x=numpy.zeros((2,2),dtype=[('x','i4'),('y','i4')]) </code></pre> <p>and the output is like this:</p> <pre><code>[[(0,0)(0,0)] [(0,0)(0,0)]] </code></pre> <p>What is the meaning of <code>[('x','i4'),('y','i4')]</code>? Please explain.</p>
<p>This is how the elements of the array are given a name and datatype.</p> <p>In this case, the names of the first elements of each entry in the array can be accessed using <code>'x'</code> and the second elements can be accessed using <code>'y'</code>:</p> <pre><code>&gt;&gt;&gt; x['x'] array([[0, 0], [0, 0]...
python|numpy
4
12,497
51,490,965
Pytorch Torch.save FileNotFoundError
<p>When I try to call "torch.save" to save my model in a "tmp_file", it rises a <code>FileNotFoundError</code>. the trace back is as follow:</p> <blockquote> <p>Traceback (most recent call last): File “C:/Users/Haoran/Documents/GitHub/dose-response/python/simulations/hdr.py”, line 234, in test_hdr_continuous() ...
<p>As <a href="https://stackoverflow.com/questions/51490965/pytorch-torch-save-filenotfounderror#comment89950953_51490965">shmee</a> observed, you are trying to write to <code>/tmp/[...]</code> on a <em>Windows</em> machine. Therefore you get <code>FileNotFoundError</code>.<br> To make your code OS agnostic, you may fi...
python|pytorch|torch
0
12,498
51,369,303
Density of distribution
<p>I want to implement function func() which completes following task: the average weight of car is <code>m</code> kg, with a standard deviation of <code>s</code> kg. What part of all cars would you expect to have weight more than <code>k</code> kg (probability must be <code>&lt;1</code>)?</p> <pre><code>import scipy....
<p><code>norm_rv.cdf(k)</code> returns the probability that the random variable takes on a value <em>less than or equal to</em> <code>k</code>.</p> <p>Your implementation should be</p> <pre><code>import scipy.stats as sts def func(m, s, k): norm_rv = sts.norm(loc=m, scale=s) return round(1 - norm_rv.cdf(k)...
python|numpy|scipy|probability|distribution
1
12,499
48,118,809
Add different color markers by day of week to a Pandas time series plot
<p>I made a time-series plot as below with customized x axis:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as mdates df = pd.DataFrame({'points': np.random.randint(1,100, 61)}, index=pd.date_range(start='11-1-2017', end='12-31-2017', freq='D')) df['dow'] = df.index.dayofweek fig, ax = plt....
<p>The only way I have seen lines plotted with different color markers is by plotting the markers as a scatter plot and then plotting the line. In this situation I would plot the dates with the marker <code>-</code> and then make a scatter plot over the top like so:</p> <pre><code>import matplotlib.pyplot as plt impor...
python|pandas|matplotlib|timeserieschart
1