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
354,200
67,660,025
ValuError: Error when checking target: expected activation_6 to have shape (70,) but got array with shape (71,)
<p>I am creating face recognition using CNN. I was following a tutorial. I am using Tensorflow==1.15.</p> <p>The programme will take 70 snaps of the user's face and save them in the folder 'dataset'</p> <p>I keep getting the error:</p> <blockquote> <p>ValueError: Error when checking target: expected activation_6 to hav...
<pre><code>ValueError: Error when checking target: expected activation_6 to have shape (70,) but got array with shape (71,) </code></pre> <p>You are feeding in 71 classes, but 70 are expected.</p> <p>Either change <code>num_classes</code> to 71, or see why you are feeding in 71 classes to <code>x_train</code>, <code>y_...
python|tensorflow|deep-learning|conv-neural-network|face-recognition
0
354,201
67,671,957
python dataframe The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I need to add data to a column from another column only if both columns don't have the same values.</p> <pre><code>... regex = &quot;|&quot;.join(v) contains_data = df[header].astype(str).str.replace(&quot; &quot;, &quot;&quot;) \ .str.lower().str.contains(regex.lower()) null_data = df[k].isna() if l...
<p>One way to achieve what you need (update k when not equal header) is by defining a function for it:</p> <pre><code>def f(x): if x['k'] != x['header']: return x['k'] + &quot;,&quot; + x['header'] else: return x['k'] </code></pre> <p>and then applying it to the dataframe under whatever cond...
python|pandas|dataframe
1
354,202
67,906,281
How do I get the day month and year columns?
<p>I'm trying to solve a regression problem trying to predict house prices, but the data frame has a non-numeric <code>date</code> column and is somewhat poorly coded. I don't want to drop the column directly. I want to get <code>day</code>, <code>month</code>, and <code>year</code> information in new columns. What sho...
<p>It's not a poorly formatted string, its a timestamp. Pandas can convert this to a datetime object for you.</p> <pre><code>import pandas as pd df = pd.DataFrame({'date':['20141013T000000','20141209T000000']}) f['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df...
python|pandas
4
354,203
67,786,694
Pandas using previous element to calculate next element
<p>I'm looking to implement the following formula in python using pandas</p> <pre><code>amS = ((1 - ratio) x (amS[-1]) + ratio x am) </code></pre> <p><code>amS[-1]</code> is the value of the variable calculated at previous time instance and <code>amS</code> is the value to be calculated at current time instance depende...
<p>If you expand that recursive formula, you get</p> <pre><code>A_n = (1-r)^n A_0 + r * \sum_{j=0}^{n-1} (1-r)^j S_{n-j} </code></pre> <p>where <code>A_n</code> and <code>S_n</code> are <code>n</code>th <code>amS</code> and <code>am</code> values, respectively and <code>r</code> is the ratio. <code>A_0</code> is the st...
python|pandas
0
354,204
67,963,990
How to reference previous row after using pandas groupby on two indexes?
<p>I'm utlizing Pandas to groupby two indexes. After performing groupby calculation, Id liek to create a two new columns that refer to the previous row.</p> <p>See code below</p> <pre><code>import pandas as pd ipl_data = { 'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings','kings', 'Kings', 'Kings', 'Riders',...
<p>IIUC, try:</p> <pre><code>import pandas as pd ipl_data = { 'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings','kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4,1,1,2,4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[...
python|pandas
2
354,205
67,782,727
Python - Delete lines from dataframe (pandas)
<p>I am trying to delete certain information from a data frame, but the 'delete-command' (.drop) does not work like it should anyone got an idea?</p> <p>My Code:</p> <pre><code> import pandas as pd def join(): open_momox_xlsx = &quot;momox_ergebnisse.xlsx&quot; open_rebuy_xlsx = &quot;rebuy_ergebnisse.xlsx...
<p>You should add <code>inplace=True</code> to <code>drop</code> function.</p>
python|pandas|dataframe
4
354,206
67,965,502
is there a way to create numpy array from a list of images?
<p>i'm trying to creat numpy array from my list that contains are 1768 images. this my code:</p> <pre><code>w = [] directory = os.listdir(PATH) directory = sorted(directory, key=len) for item in directory: img = Image.open(os.path.join(PATH, item)) w.append(img) count+=1 print('w_shape: ', np.array(w, dtype...
<p>You are getting this error because each element of you list is a 'JpegImageFile' which is not compatible with <code>float()</code>. To avoid this, add the images directly as arrays to your list.<br /> You can use <code>np.asarray()</code> to read the image as a numpy array. Check out the code snippet below:</p> <pre...
python|numpy
0
354,207
67,976,027
how to convert python dictionary into required data frame output?
<p>lets say I am getting api response as</p> <pre><code>response= { 'id': {'abc':[{'area_code':'mkt','area_name':'market'},{'area_code':'chdi','area_name':'chandani'}], {'xyz':[{'area_code':'rlr','area_name':'rural'},{'area_code':'rwl_st','area_name':'railway station'}]} }} </code></pre> <p>I wanted to convert it to da...
<p>Your response must look like this to work:</p> <pre class="lang-py prettyprint-override"><code>response = { &quot;id&quot;:{ &quot;abc&quot;:[ { &quot;area_code&quot;:&quot;mkt&quot;, &quot;area_name&quot;:&quot;market&quot; }, { &quot;area_code...
python|json|pandas|data-science
0
354,208
68,015,792
Grouping Pandas DataFrame with NaNs
<p>I have a DataFrame <code>df1</code></p> <pre><code>df1 = pd.DataFrame({ &quot;id&quot;: [1, 1, 2, 2, 3, 3], &quot;text&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, np.nan, np.nan], &quot;value1&quot;: [2, np.nan, 6, np.nan, 7, np.nan], &quot;value2&quot;: [np.nan, 8, np.nan, 1,...
<p>Just groupby <code>id</code>, call the <code>first</code> and reset the index.</p> <pre class="lang-py prettyprint-override"><code>df1.groupby('id').first().reset_index() id text value1 value2 value3 0 1 a 2.0 8.0 NaN 1 2 b 6.0 1.0 NaN 2 3 None 7.0 9.0 NaN <...
python|pandas|dataframe|pandas-groupby|nan
1
354,209
67,979,142
Scale specific columns in pandas dataframe using MinMaxScaler
<p>I want to rescale my pandas dataframe using sklearn's MinMaxScaler function, like in <a href="https://www.geeksforgeeks.org/how-to-scale-pandas-dataframe-columns/" rel="nofollow noreferrer">this</a> tutorial.</p> <p>The data I have is in <code>mydata</code>,</p> <pre><code> x1 x2 x3 x4 x5 Date ...
<p>I found a solution:</p> <pre><code>mydata[['x1','x2','x3']] = MinMaxScaler().fit_transform(mydata[['x1','x2','x3']]) </code></pre> <p>It's similar to the solution in <a href="https://stackoverflow.com/questions/49641707/standardize-some-columns-in-python-pandas-dataframe">Standardize some columns in Python Pandas da...
python|pandas|scikit-learn|rescale
1
354,210
67,694,215
pandas sort values in pivot table
<p>I have a dataframe and I want to get all rows grouped in id where after row with country = russia and month = march is followed by a line with country != russia</p> <p>input dataframe:</p> <pre><code>import pandas as pd import numpy as np data = {'fruit': ['pear','pear','pear','banana', 'banana', 'banana', 'apricot'...
<p>Is this your desired outcome? It is &quot;to get rows with figures no less than 3&quot;, but different from your outcome picture..</p> <pre><code>df = df.pivot_table(index=['fruit','country'], columns='id1', values='id', aggfunc='count') df['total'] = df.sum(axis=1) df.drop(df.loc[df['total']&lt;3].index, inplace=Tr...
python|pandas|pivot|pivot-table
0
354,211
67,978,016
Program stops running when it does not exist, try in for loop?
<p>I'm trying to download from the logins by adding a suffix: the for loop works well i.e. I managed to download the sequences until this url does not exist and the execution stops. So I want that if this url doesn't exist, the script finishes running. Also, I would like to please also put all the output files in a fol...
<p>You have put your <strong>loop</strong> inside the <code>try</code> block, so whenever a url is not found, it throws an error and moves out of the loop, then caught by the <code>except</code> block. This stops the execution of your script. To fix it, put <strong><code>try-except</code></strong> block inside of your ...
python|pandas|dataframe
1
354,212
67,995,003
Convert Pandas column of List values to headers with counts
<p>I'm trying to reshape the dataset <code>df</code> below to show the <code>values</code> lists as column headers and the frequency they appear as the value (desired output shown at bottom). TBH I'm a little stumped as how to move forward; like should I make a dataframe with the appropriate rows and columns and then a...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html#pandas-dataframe-explode" rel="nofollow noreferrer"><code>explode</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html#pandas-crosstab" rel="nofollow noreferrer"><cod...
python|pandas
2
354,213
67,906,861
Convert nested CSV to nested JSON using Pandas
<p>I have a dataframe like this</p> <pre><code>org.iden.account,org.iden.id,adress.city,adress.country,person.name.fullname,person.gender,person.birthYear,subs.id,subs.subs1.birthday,subs.subs1.org.address.country,subs.subs1.org.address.strret1,subs.org.buyer.email.address,subs.org.buyer.phone.number account123,id123,r...
<pre><code>def df_to_json(row): tree = {} for item in row.index: t = tree for part in item.split('.'): prev, t = t, t.setdefault(part, {}) prev[part] = row[item] return tree </code></pre> <pre><code>&gt;&gt;&gt; df.apply(df_to_json, axis='columns').tolist() [{'org': {'id...
json|python-3.x|pandas|dataframe|csv
1
354,214
67,914,051
converting dictionary into dataframe as expected output in python
<p>let's say i have a dictionary as</p> <pre><code>dj= { &quot;totalrecords&quot;: 2, &quot;data&quot;: [ { &quot;stateCd&quot;: &quot;U.K&quot;, &quot;stateName&quot;: &quot;uttarakhand&quot;, &quot;details&quot;: { &quot;...
<p>You can try something like this</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">Reference</a></p> <pre class="lang-py prettyprint-override"><code> data = [{'state': 'Florida', 'shortname': 'FL', 'info': {'gover...
python|json|pandas|data-science
2
354,215
67,931,682
find days between 2 dates in python but only number
<p>I was trying to find difference of a series of dates and a date. for example, the series is from may1 to june1 which is</p> <pre><code>date = pd.DataFrame() In [0]: date['test'] = pd.date_range(&quot;2021-05-01&quot;, &quot;2021-06-01&quot;, freq = &quot;D&quot;) Out[0]: date test 0 2021-05-01 00:00:00 1 ...
<p>You don't need to create a column <code>base</code> for this, simply do:</p> <pre><code>&gt;&gt;&gt; (date['test'] - pd.to_datetime(&quot;2021-05-01&quot;, format='%Y-%m-%d')).dt.days 0 0 1 1 2 2 3 3 4 4 ... 27 27 28 28 29 29 30 30 31 31 Name: test, dtype: int64 </code></pre>
python|pandas|datetime
1
354,216
67,837,675
Python3 pandas dataframe round .5 always up
<p>According to the <a href="https://docs.python.org/3/library/functions.html#round" rel="nofollow noreferrer">documentation</a>, Python rounds values toward the even choice if the upper and lower rounded values are equally close to the original number.</p> <p>I want to round values in my <code>pandas.DataFrame</code> ...
<p>Using the <code>decimal</code> module, you could do</p> <pre><code>import decimal df = pd.DataFrame(data=[0.5, 1.499999, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5], columns=[&quot;orig&quot;]) df.orig = df.orig.apply( lambda x: decimal.Decimal(x).to_integral_value(rounding=decimal.ROUND_HALF_UP) ) </code></pre>
python|pandas|rounding
1
354,217
67,668,873
Fitting Keras model with Tensorflow datasets
<p>I'm reading <a href="https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/" rel="nofollow noreferrer">Aurélien Géron's book</a>, and on chapter 13, I'm trying to use Tensorflow datasets (rather than Numpy arrays) to train Keras models.</p> <h3>1. The dataset</h3> <p>The dataset comes from <...
<p>Just as the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Sequential#fit" rel="nofollow noreferrer">official docs</a> for <code>tf.keras.Sequential</code> suggest, no <code>batch_size</code> needs to be provided when <code>inputs</code> are instances of <code>tf.data.Dataset</code> while calling <code...
python|numpy|tensorflow|machine-learning|keras
2
354,218
67,870,887
Trouble understanding behaviour of modified VGG16 forward method (Pytorch)
<p>I have modified VGG16 in pytorch to insert things like BN and dropout within the feature extractor. By chance I now noticed something strange when I changed the definition of the forward method from:</p> <pre><code>def forward(self, x): x = self.model(x) return x </code></pre> <p>to:</p> <pre><code>def forwa...
<p>I can't run your code, but I believe the issue is because linear layers expect 2d data input (as it is really a matrix multiplication), while you provide 4d input (with dims 2 and 3 of size 1).</p> <p>Please try <a href="https://pytorch.org/docs/stable/generated/torch.squeeze.html" rel="nofollow noreferrer">squeeze<...
python|deep-learning|neural-network|pytorch|conv-neural-network
2
354,219
67,834,297
How can I save a file using encoding UTF-16-BE with Python?
<p>I am working with a Pandas dataframe and I need to save it into a file with an encoding type I have never used: UTF-16-BE. I understood that this encoding is not the &quot;standard&quot; UTF-16, which is managed by Python read/write functions.</p> <p>That is what I found in another question:</p> <ul> <li>The <code>B...
<p>Per your comment about using <code>pandas</code> and <code>df.to_csv</code> here's an example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import csv df = pd.DataFrame([['dog','狗'],['cat','猫']],columns=['English','中文']) df.to_csv('out.csv',encoding='utf-16be',index=False) # Verification...
python-3.x|pandas|character-encoding|utf-16
0
354,220
67,939,205
Dot product with sparse matrix and vector
<p>Im having a very hard time trying to program a dot product with a matrix in sparse format and a vector.<br> <br> My matrix have the shape 3 x 3 in the folowing format: <br></p> <pre><code>Ms=[[0, 0, 0.6153414193508929],[1, 1, 0.9884632853575251],[2, 1, 0.22943483758936845],[2, 2, 0.336180557968783]] </code></pre> <p...
<p>You can take advantage of the fact that if <code>A</code> is a matrix of shape <code>(M, N)</code>, and <code>b</code> is a vector of shape <code>(N, 1)</code>, then <code>A.b</code> equals a vector <code>c</code> of shape <code>(M, 1)</code>.</p> <p>A row <code>x_c</code> in <code>c</code> = <code>sum((x_A, a row i...
python|numpy|for-loop|matrix|vector
1
354,221
67,718,254
I get this error every time I log into my registered account through face recognition
<p>I get this error every time I log into my registered account through face recognition. Please suggest what should I do.</p> <pre><code> Exception in Tkinter callback Traceback (most recent call last): File &quot;C:\Users\Claire\AppData\Roaming\Python\Python36\site-packages\pandas\core\indexes\base.py&quot;, line 2...
<pre><code>def TrackImages(UserId): recognizer = cv2.face.LBPHFaceRecognizer_create()#cv2.createLBPHFaceRecognizer() recognizer.read(&quot;TrainingImageLabel\Trainner.yml&quot;) harcascadePath = &quot;haarcascade_frontalface_default.xml&quot; faceCascade = cv2.CascadeClassifier(harcascadePath); df=pd.read_csv(&quot;Det...
python|pandas
0
354,222
67,881,322
Why can't SciPy's curve_fit find the covariance/give me sensical parameters for this higher order gaussian function?
<p>Here's some minimal code:</p> <pre><code>from scipy.optimize import curve_fit xdata = [16.530468600170202, 16.86156794563677, 17.19266729110334, 17.523766636569913, 17.854865982036483, 18.18596532750305, 18.51706467296962, 18.848164018436194, 19.179263363902763, 19.510362709369332] ydata = [394, 1121, 1173, 1196, ...
<p>I believe you are running into this problem because <code>curve_fit</code> is also testing non-integer values of <code>n</code>, in which case your function <code>gauss</code> returns complex values when <code>x&lt;x_o</code>.</p> <p>I believe it would be easier to brute-force your way through every integer <code>n<...
python|numpy|scipy|curve-fitting
2
354,223
67,956,206
Index numpy array with multiple ranges
<p>Imagine an array <code>a</code> which has to be indexed by multiple ranges in <code>idx</code>:</p> <pre><code>In [1]: a = np.array([7,9,1,2,3,5,6,8,1,0,]) idx = np.array([[0,3],[5,7],[8,9]]) a, idx Out[1]: (array([7, 9, 1, 2, 3, 5, 6, 8, 1, 0]), array([[0, 3], [5, 7], ...
<p>You can try vectorizing <code>slice</code> itself:</p> <pre><code>&gt;&gt;&gt; slice_np = np.vectorize(slice) &gt;&gt;&gt; slice_idx = tuple(slice_np(idx[:, 0], idx[:, 1])) &gt;&gt;&gt; a[np.r_[slice_idx]] array([7, 9, 1, 5, 6, 1]) </code></pre>
python|arrays|numpy|indexing
0
354,224
67,682,293
Confusion between `|` and `&` in Pandas operation
<p>I am trying to split the following pandas dataframe into two based on the condition that the (<code>saleMonth</code>,<code>saleYear</code>) be before (5,2010) or before May, 2010.</p> <p>df:</p> <p><a href="https://i.stack.imgur.com/fCgot.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fCgot.png" ...
<pre><code>df[(df['saleMonth'] &lt; 5) &amp; (df['saleYear'] &lt; 2010)] </code></pre> <p>Here you are asking to return all rows that have a saleMonth below 5 AND a saleYear below 2010. So if one of the statements is not true it should not return the row. This should return rows 1 and 2 of your sample data. Row 0 has a...
python|pandas|dataframe
0
354,225
67,989,539
AttributeError: set_model Error (Keras callbacks)
<p>I am fitting a model using Keras and passed the callbacks list to the model fit, but encountered the following error. What am I doing wrong here?</p> <pre><code> from tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping, Callback checkpoint = ModelCheckpoint(f'model{i}.h5'...
<p><strong>sometimes if you write in the list all required callbacks it accepts but sometimes you should assign it to another variable then write it like this.</strong> history = model.fit( train_generator, validation_data = valid_generator, epochs=10, verbose=1, callbacks= [my_callbacks]) <strong>may your model.fit() ...
python|tensorflow|keras|callback
1
354,226
67,783,540
Easy method to subtract all the columns from one reference column .Sum and square it and store it
<p>Basically I am subtracting all the columns with respect to reference column and then summing and squaring the value. There is one column named <code>ReferenceSpeed</code> and columns <code>speed1,speed2,speed3.....</code> I am just subtracting all the speeds (1, 2, 3....) with respect to the <code>ReferenceSpeed</co...
<p>You don't need to do that all in loops, that will be slow. You are already using <code>pandas</code> and <code>numpy</code>, so take the advantage of <strong>vectorized</strong> operations they provide.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('F:\\Pytho...
python|pandas|dataframe|numpy
0
354,227
67,847,881
Convert yolov4-tiny to transflow lite: ValueError: cannot reshape array of size 374698 into shape (256,256,3,3)
<p>As I try to covert my yolov4-tiny custom weight to tftile, it always happen.</p> <p>This is what I input:</p> <pre><code>python save_model.py --weights ./data/yolov4-tiny-obj-food_final.weights --output ./checkpoints/yolov4-tiny-416-tflite --input_size 416 --model yolov4 --framework tflite </code></pre> <p>And the w...
<h1>Short answer</h1> <p>You have to add <code>--tiny</code> to the command. Which, from the command you gave in the question, will be.</p> <pre><code>python save_model.py --weights ./data/yolov4-tiny-obj-food_final.weights --output ./checkpoints/yolov4-tiny-416-tflite --input_size 416 --model yolov4 --framework tflite...
python|tensorflow-lite|yolov4
0
354,228
67,914,116
How to extract a segmented object after it has been masked using Maskrcnn
<p>I have an image. I am using Matterports Maskrcnn algorithm to perform segmentation. Now I have the segmented masks aftr detection. I want to extract this object and then create a new blank image (black background) of the same initial image size and just put this masked object in the same exact position as in the ori...
<p>Looks like <code>results[0]['masks']</code> is the information you need and you can just mask the original image like this</p> <pre class="lang-py prettyprint-override"><code># Rows x Columns x Classes masks = results[0]['masks'] # if pixel is 1 for any class mask = np.any(masks.astype(np.bool), axis=-1) # apply mas...
python|numpy|tensorflow|deep-learning|artificial-intelligence
0
354,229
67,627,443
how to covert substrings of a list into one single sting
<p>I generated a list of tuples into a list.Then i wanted to remove all the tupple brackets and convert the whole list into one single list of a string.I tried doing this:</p> <pre><code>from itertools import permutations l=[] m=[] perm = permutations([2,3,5,7], 4) for i in list(perm): #print (i) l.append(i) f...
<p><code>permutation</code> gives list like</p> <pre><code>[(2, 3, 5, 7), (2, 3, 7, 5), ...] </code></pre> <p>which you can convert to list of strings</p> <pre><code>['2357', '2375', '2537'. ...] </code></pre> <p>using</p> <pre><code> &quot;%s%s%s%s&quot; % data </code></pre> <p>without commans and spaces.</p> <p>And ...
python|pandas|string|list|concatenation
1
354,230
31,709,241
Pandas data-frame ungrouping functionality
<p>I have a dataframe with 3 columns:</p> <pre><code>df1 = pd.DataFrame([[2, 2, 5, 7], [2, 5, 7.5, 10], [2, 5, 1, 3]]).T df1.columns = ['col1', 'col2', 'col3'] df1 col1 col2 col3 0 2 2.0 2 1 2 5.0 5 2 5 7.5 1 3 7 10.0 3 </code></pre> <p>Now I want to ungroup the 3rd column...
<p>Here is one way to use <code>groupby</code> with <code>reindex</code>.</p> <pre><code># custom apply function def func(group): return group.reset_index(drop=True).reindex(np.arange(group.col3)).fillna(method='ffill') # groupby apply result = df1.groupby(level=0).apply(func) col1 col2 col3 0 0 2 2...
python-2.7|pandas|dataframe
1
354,231
31,926,454
importing converted data using pandas
<p>I have a csv file that looks like this:</p> <pre><code>patient_id age_in_years CENSUS_REGION URBAN_RURAL_STATUS YEAR MONTH DAY_NUMBER_IN_MONTH race 11511 7 Northeast Urban 2011 6 20 Other 9882613 73 South Urban 2011 7 25 Unknown 32190339 49 West Urban 2011 8 13 Ca...
<p>If you're just iterating over that series to build a list of floats, you could instead use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow">astype</a>(float). </p> <p>It seems like you have some values in that column, though, that cannot be converted to flo...
python|csv|pandas|linear-regression
1
354,232
31,971,185
Segfault when import_array not in same translation unit
<p>I'm having problems getting the NumPy C API to properly initialize. I think I've isolated the problem to calling <code>import_array</code> from a different translation unit, but I don't know why this should matter.</p> <p>Minimal working example:</p> <p><strong>header1.hpp</strong></p> <pre><code>#ifndef HEADER1_...
<p>After digging through the NumPy headers, I think I've found a solution:</p> <p>in <code>numpy/__multiarray_api.h</code>, there's a section dealing with where an internal API buffer should be. For conciseness, here's the relevant snippet:</p> <pre><code>#if defined(PY_ARRAY_UNIQUE_SYMBOL) #define PyArray_API PY_ARR...
python|c++|python-2.7|python-3.x|numpy
7
354,233
32,132,388
Looping through slices of Theano tensor
<p>I have two 2D Theano tensors, call them <code>x_1</code> and <code>x_2</code>, and suppose for the sake of example, both <code>x_1</code> and <code>x_2</code> have shape (1, 50). Now, to compute their mean squared error, I simply run:</p> <pre><code> T.sqr(x_1 - x_2).mean(axis = -1). </code></pre> <p>However, w...
<p>Similar to what can be done in <code>numpy</code>, a solution would be to reshape your (1, 50) tensor to a (1, 10, 5) tensor (or even a (10, 5) tensor), and then to compute the mean along the second axis.</p> <p>To illustrate this with numpy, suppose I want to compute means by slices of 2</p> <pre><code>x = np.arr...
arrays|python-2.7|numpy|slice|theano
1
354,234
32,124,706
Separating pandas dataframe by offset string
<p>Lets say I have a <code>pandas.DataFrame</code> that has hourly data for 3 days:</p> <pre><code>import pandas as pd import numpy as np import datetime as dt dates = pd.date_range('20130101', periods=3*24, freq='H') df = pd.DataFrame(np.random.randn(3*24,2),index=dates,columns=list('AB')) </code></pre> <p>I would l...
<p>Ok, so this sounds like a textbook case for using <code>groupby</code>. Here's my thinking:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd #let's define a function that'll group a datetime-indexed dataframe by hour-interval/date def create_date_hour_groups(df, hr): new_df = df.copy() ...
python|numpy|pandas
1
354,235
31,855,249
Creating a label dataset from a segmented image using Python
<p>I've labeled an image to produce a numpy array with labels e.g.</p> <pre><code>array([[0, 1, 0, ..., 0, 0, 0], [0, 1, 0, ..., 0, 0, 0], [0, 1, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [2, 2, 0, ..., 0, 0, 0], [2, 2, 0, ..., 0, 0, 0]], dtype=uint8)} </code></pr...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow"><code>np.vstack</code></a> to create a <code>Nx3</code> numpy array having a s...
python|numpy|scikit-learn|scikit-image
1
354,236
31,848,877
How to replace string values in pandas dataframe to integers?
<p>I have a Pandas DataFrame that contains several string values. I want to replace them with integer values in order to calculate similarities. For example:</p> <pre><code>stores[['CNPJ_Store_Code','region','total_facings']].head() Out[24]: CNPJ_Store_Code region total_facings 1 93209765046613 Geo RS/...
<p>You can use the <code>.apply()</code> function and a dictionary to map all known string values to their corresponding integer values:</p> <pre><code>region_dictionary = {'Geo RS/SC': 1, 'Geo PR/SPI' : 2, .... } stores['region'] = stores['region'].apply(lambda x: region_dictionary[x]) </code></pre>
python|pandas|dataframe|cosine-similarity
7
354,237
31,893,930
Download CSV from an iPython Notebook
<p>I run an iPython Notebook server, and would like users to be able to download a pandas dataframe as a csv file so that they can use it in their own environment. There's no personal data, so if the solution involves writing the file at the server (which I can do) and then downloading that file, I'd be happy with that...
<p>How about using the FileLinks class from IPython? I use this to provide access to data directly from Jupyter notebooks. Assuming your data is in pandas dataframe p_df:</p> <pre><code>from IPython.display import FileLink, FileLinks p_df.to_csv('/path/to/data.csv', index=False) p_df.to_excel('/path/to/data.xlsx', in...
csv|pandas|ipython-notebook
41
354,238
31,838,559
Is dataframe created using toPandas() method is distributed across the spark cluster?
<p>I am reading a CSV through </p> <pre><code>data=sc.textFile("filename") Df = Sparksql.create dataframe() Pdf = Df.toPandas () </code></pre> <p>Now is Pdf distributed across the spark cluster or it resides in the environment of host machine??</p>
<p><strong>No.</strong></p> <p>As it says in the PySpark <a href="https://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py" rel="nofollow noreferrer">source code of DataFrame</a>:</p> <pre><code> .. note:: This method should only be used if the resulting Pandas's DataFrame is expected to...
pandas|apache-spark|pyspark|pyspark-sql
1
354,239
31,872,693
How do I columnwise reduce a pandas dataframe?
<p>I have a dataframe as shown below:</p> <pre><code>try: from StringIO import StringIO except ImportError: from io import StringIO from functools import reduce import pandas as pd from numpy import uint8, logical_or df = pd.read_table(StringIO("""a b c 1 0 0 1 1 1 0 1 1 1 1 0"""), ...
<p>I believe this is the "pandastic" way to achieve this</p> <pre><code>df.apply(lambda x: reduce(logical_or,x), axis=1) </code></pre> <p>although there might be other routes.</p>
python|pandas
10
354,240
41,649,968
How to vectorize and devectorize using sklearn's CountVectorizer?
<p>I want to vectorize some text to corresponding integers and then convert those text to its mapped integers and also create new sentence using new input integers <code>[2,9,39,46,56,12,89,9]</code>.</p> <p>I have seen some custom functions which can used for this purpose but I want to know whether sklearn itself has...
<p>For vectorizing sentence into integers you can use <code>transform</code> function. Output of this function is vector with counts for each term - feature vector.</p> <pre><code>vec = CountVectorizer() vec.fit(a) print vec.vocabulary_ new_sentence = "dolor nulla enim" mapped_a = vec.transform([new_sentence]) print ...
python|scikit-learn|sklearn-pandas
5
354,241
41,540,340
Large scale pivot table in Python
<p>I have 100-300Go data under csv format(numerical + unicode text) and needs to do regular Pivot Table jobs on this. After googling/StackOverflow-ing, could not find satisfactory answer (only partial). Wondering which solution is the fastest for single machine (64Go RAM):</p> <p>1) Convert and Insert into PostGres ...
<p>The questioner must have solve the problem , for others whom might land upon this question , my answer might help. Try this solution (convert it as per your dataset) , I tried on 50-80 GB it worked adding numpy will improve the performance.</p> <pre><code>import pandas as pd from datetime import date from datetime i...
pandas|pivot-table|bigdata
0
354,242
41,301,430
Tensorboard is not running in Google Chrome
<p>After launching tensorboard using:</p> <pre><code>$ tensorboard --logdir=/home/kv/data2/debug/Summaries/train/ --host 127.0.0.1 --port 6666 </code></pre> <p>I get:</p> <blockquote> <p>503 Service Unavailable</p> <p>Failed to connect to server 127.0.0.1</p> </blockquote> <p>In Google Chrome (Ubuntu 14.04 LTS, tensorf...
<p>Have you configured Chrome to not use your proxy for 127.0.0.1? Possibly by using <code>--proxy-bypass-list</code>?</p>
javascript|google-chrome|firefox|tensorflow|tensorboard
1
354,243
41,338,859
Running a TensorFlow Image Recognition API to search for an object
<p>TensorFlow has an api using the inception v3 model for identifying objects. I was wondering, if there was any way to locate smaller images in a larger image. For example, locating all oranges on an orange tree. I tried splitting the larger image into a grid of smaller images and applying tensorflow on each individua...
<p>The term you're looking for is <em>object detection</em>. You can use a sliding window at different scales. This is one way, there's probably better ones out there, but I don't know what they are.</p> <p>Let's say some oranges are closer than others. Start with a 10x10 (or something) box in the top left corner, and...
tensorflow|image-segmentation|image-recognition
1
354,244
41,604,253
How to fine tune the hyper-parameters of ftrl optimizer in tensorflow
<p>I found the initial parameters of FTRL optimizer is:</p> <pre><code>learning_rate_power: -0.5, initial_accumulator_value: 0.1, l1_regularization_strength: 0.0, l2_regularization_strength: 0.0 </code></pre> <p>But how could I fine-tune the parameters to make it better?</p>
<p>You should perform hyper parameter tuning - Keep a test dataset on the side, and then split your train dataset to train and cross validation sets.</p> <p>You can then use the validation dataset for tuning these parameters, or directly perform this on the train dataset. You could do grid search over all parameters, ...
tensorflow
-1
354,245
41,272,293
Converting a correlateion coefficient function from NumPy to Dask
<p>I'm trying to evaluate dask by converting a method from <a href="http://thunder-project.org/" rel="nofollow noreferrer">thunder</a> (using Spark), to the equivalent numpy version, but I'm not sure how to write this using dask/distributed.</p> <p>In thunder, I can take a stack of images, convert it to a series, and ...
<p>Perhaps something like the following?</p> <pre><code>import dask.array as da import numpy as np imgs = da.random.random((10, 900, 900), chunks=(1, 900, 900)) reshaped = imgs.reshape((10, 900 * 900)) </code></pre> <p>If you wanted to correlate your images against each other</p> <pre><code>result = da.corrcoef(res...
python|numpy|distributed|dask
2
354,246
41,543,849
checkin if char in dataframe
<p>I want to save a pandas <code>dataframe</code> as a <code>csv</code> file, but I have trouble finding a good separator : If I save the <code>dataframe</code> and load the saved filed, I have mixed columns.</p> <p>So I need to check if some char are in my <code>dataframe</code> and would cause this issue.</p> <p>I'...
<p>You need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow noreferrer"><code>any</code></a> for check at least one <code>True</code> because compare <code>boolean Series</code>, not scalar values <code>True</code> or <code>False</code>:</p> <pre><code>if df[col...
python|pandas
1
354,247
41,414,867
Tensorflow: You must feed a value for placeholder tensor 'Placeholder' with dtype float [but the value is a float]
<p>I am going through a tensorflow tutorial and keep getting this error:</p> <pre><code>InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/c...
<p>You have an error in the <code>print()</code> statement. Luckily, it was picked up for me as a <code>SyntaxError</code> as I use TensorFlow r0.11.</p> <p>Replace,</p> <pre><code>print(sess.run(loss), feed_dict={xs:x_data, ys:y_data}) </code></pre> <p>with,</p> <pre><code>print(sess.run(loss, feed_dict={xs:x_data...
python|numpy|tensorflow
3
354,248
41,526,858
Inception retraining issue "Nan in summary histogram for: HistogramSummary"
<p>I'm trying to retrain inceptionV3 on my RPi3. I'm getting this histogram error message.</p> <pre><code>python /home/pi/Tensorflow/tensorflow/tensorflow/examples/image_retraining/retrain.py --bottleneck_dir=/home/pi/Documents/Machine\ Learning/Inception/tf_files/bottlenecks --how_many_training_steps 500 --model_dir=...
<p>Sounds like that it might help to know where the NaN values are coming from. For that, take a look at tensorflow debugger (tfdbg): <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/debugger/index.md" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/...
python|tensorflow|imagenet
3
354,249
41,452,231
Modify plot with dots instead of horizontal lines and more granular y axis values
<p><strong>Question:</strong></p> <p>Using this data and the following code creates a plot showing horizontal lines for the <code>nlargest</code> values from the <code>'# of Trades'</code> column. </p> <p>How do we show these <code>nlargest</code> values as a dot (is scatter plot the correct terminology?) which is p...
<h3>Modified Answer based on comment</h3> <pre><code>axnum = df[['High','Low']].plot() axnum.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) axnum.yaxis.set_major_locator(ticker.MultipleLocator(.05)) data = df.nlargest(5, '# of Trades')[['High', 'Low']] plt.scatter(data.index, data.High, color='r', s=np....
python|pandas|matplotlib
1
354,250
41,507,040
Sort all columns of a dataframe
<p>I have a dataframe of 2000 rows and 500 columns. I want to sort every column in ascending order. The columns don't have names they're just numbered 0-500.</p> <p>Random data: <code>df = pandas.DataFrame(np.random.randint(0,100,size=(2000, 500)), columns=range(500))</code></p> <p>Using <code>df.sort_values(by=0,axi...
<p>I think you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>numpy.sort</code></a> with <code>DataFrame</code> constructor or <code>apply</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html" re...
python|sorting|pandas|dataframe
13
354,251
41,669,995
Python ValueError: non-broadcastable output operand with shape (124,1) doesn't match the broadcast shape (124,13)
<p>I would like to normalize a training and test data set using <code>MinMaxScaler</code> in <code>sklearn.preprocessing</code>. However, the package does not appear to be accepting my test data set.</p> <pre><code>import pandas as pd import numpy as np # Read in data. df_wine = pd.read_csv('https://archive.ics.uci.e...
<p>The partitioning of train/test data must be specified in the same order as the input array to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer"><code>train_test_split()</code></a> function for it to unpack them corresponding to that...
python|python-2.7|numpy|scikit-learn
4
354,252
41,651,731
Unpacking a list in python using .T?
<p>I'm using scipy's method integrate.odeint to solve a second order LDE. The method requires that the equation be put in the form of a system of two first-order equations in two unknowns. The method</p> <pre><code>odeint(system_matrix,initial_conditions_matrix,time_values) </code></pre> <p>outputs the solution vecto...
<p><code>odeint(system_matrix,initial_conditions_matrix,time_values)</code> is a matrix of 2 columns.</p> <p>To be able to get the first column, first use <code>.T</code> (transpose) and then you are able to unpack since the elements are oriented like you want.</p> <p>BTW I doubt that <code>u'</code> is a valid varia...
python|list|numpy|scipy
3
354,253
41,361,151
python pandas: create multiple empty dataframes
<p>I am trying to create multiple empty pandas dataframes in the following way:</p> <p><code>dfnames = ['df0', 'df1', 'df2'] x = pd.Dataframes for x in dfnames</code></p> <p>The above mentionned line returns error syntax. What would be the correct way to create the dataframes?</p>
<p>If you want to create variables that contain empty DataFrames, this will do what you need:</p> <pre><code>dfnames = ['df0', 'df1', 'df2'] for x in dfnames: exec(x + ' = pd.DataFrame()') </code></pre>
python|pandas
3
354,254
41,507,430
Get data sequentially from numpy array in Matlab ordering
<p>As an example, suppose, in Matlab, a Matrix <code>a(2,3,2)</code> like this:</p> <pre><code>a(:,:,1) = 1 2 3 4 5 6 a(:,:,2) = 7 8 9 10 11 12 </code></pre> <p>If I use <code>mex</code> and access the elements of this matrix sequentially, I get the following order...
<p>This bugs a lot of people going into NumPy/Python from MATLAB. So, in MATLAB, the indexing format is <code>(column x row x dim3)</code> and so on. With NumPy, it's <code>(axis-0, axis-1, axis-2)</code> and so on.</p> <p>To show this schematically using a sample case on MATLAB :</p> <pre><code>&gt;&gt; a = reshape(...
python|matlab|numpy
6
354,255
41,415,175
Python Numpy Memory Error
<p>I'm trying to compare two lists of MD5 hashes and identify matches. One of these lists contains approximately 34,000,000 hashes, and the other could contain up to 1,000,000. </p> <p>Using Numpy I've been experimenting with the time is takes to conduct the comparison vs a standard python array, and the performance d...
<p>With that routine:</p> <pre><code>def read_sample_data_01_array(): sample_data_01 = [] with open("data_set_01.txt", "r") as fi: #34,000,000 hashes for line in fi: sample_data_01.append(line) np_array_01 = np.array(sample_data_01) return(np_array_01) </code></pre> <p>you're creat...
python|arrays|numpy
1
354,256
41,449,054
Query Dataframe Column on String Values
<p>I need to grab values where the column startswith either value <code>'MA', 'KP'</code>.</p> <p>I am trying to chain my dataframe query as such:</p> <pre><code>df.loc[df['REFERRAL_GRP'].str.startswith("KP")==True | df['REFERRAL_GRP'].str.startswith("MA")==True] </code></pre> <p>This doesn't seem to work because th...
<p>try numpy <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html" rel="nofollow noreferrer">logical_or</a> </p> <pre><code>import numpy as np df.loc[np.logical_or(df['REFERRAL_GRP'].str.startswith("KP")==True , df['REFERRAL_GRP'].str.startswith("MA")==True)] </code></pre>
python|pandas|dataframe
2
354,257
41,343,206
Pandas cannot convert input to timestamp error
<p>I have two variables in the data set beginning date (format datetime64[ns]) and end date(format datetime64[ns]). I'm using following code to get the dates between beginning date and end date.</p> <pre><code>pd.date_range(start = data['beginning_date'], end = data['end_date'], freq = 'D') </code></pre> <p>but it's ...
<p>Assuming you have the following DF:</p> <pre><code>In [30]: df Out[30]: beginning_date end_date 0 2013-12-22 2014-01-01 1 2009-12-14 2009-12-28 2 2010-12-31 2011-01-11 </code></pre> <p>I guess you tried to use <strong>series</strong> instead of <strong>scalar</strong> values when calling <code>pd.d...
python|pandas
5
354,258
41,556,020
Pandas: Column that is dependent on another value
<p>I have a Pandas dataframe like the following:</p> <pre><code> col1 col2 col3 col4 0 5 1 11 9 1 2 3 14 7 2 6 5 54 8 3 11 2 67 44 4 23 8 2 23 5 1 5 9 8 6 9 7 45 71 </code></pre> <p>I want to make a 5th column (...
<p>You can use multiple <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a>, if no condition is <code>True</code> (<code>col1 =&gt; 50</code>) was added last value <code>1</code>:</p> <pre><code>df['col5'] = np.where(df['col1'] &lt;3, df['...
python|pandas|if-statement|conditional-statements|multiple-columns
7
354,259
41,560,982
How to use TensorFlow in R if I have Anaconda Python already installed?
<p>In the <a href="https://rstudio.github.io/tensorflow/" rel="nofollow noreferrer">guide about using TensorFlow</a> in R, they suggest not to use the Anaconda TensorFlow installation. Does this mean Anaconda Python cannot coexist with using TensorFlow in R?</p>
<p>There is an issue using anaconda along with R. Please follow <a href="https://github.com/rstudio/tensorflow" rel="nofollow noreferrer">this</a> link for more info. </p> <p>Directly from the link above:</p> <p>TensorFlow for R is currently only compatible with OS X and Linux (support for Windows will likely be adde...
python|r|tensorflow|anaconda
2
354,260
41,596,182
What do I need to specify in order for pandas to_csv to keep leading zeros
<p>I have a excel file and I read into a dataframe. I'd like to output this df to CSV file. But one of the columns (labeled <code>id</code>) in CSV file are integer like 1 ,but wanna output string like"0001"with leading zeros.<br> Every time I try to output the file, it interprets this column as integer and removes th...
<p>You can control the type and format of input columns with the <code>converters</code> parameter. The following example accomplishes what you're after.</p> <ul> <li>Make sure to use your <code>filename</code> in place of <code>StringIO(txt)</code></li> <li>The converter parameter takes a dictionary with the key bei...
python|pandas|export-to-csv
0
354,261
41,644,059
why int conversion is so much slower than float in pandas?
<p>I have a 4Gb CSV file with strictly integer data I want to read into pandas DataFrame. Native read_csv consumes all RAM (64Gb) and fails with MemoryError. With explicit dtype, it just takes forever (tried both int and float types). </p> <p>So, I wrote my own reader:</p> <pre><code>def read_csv(fname): import c...
<p>I suggest you use numpy array for this, for example:</p> <pre><code>def read_csv(fname): import csv reader = csv.reader(open(fname)) names = reader.next()[1:] # first row n = len(names) data = np.empty((n, n), np.int32) tag_map = {name:i for i, name in enumerate(names)} for row in reade...
python|pandas
1
354,262
27,895,422
Python: DEAP: programatically handle number of func parameters
<p>In the evaluate function (for a genetic programming symbolic regression problem with binary input/output), I want to be able to programmatically handle functions that have different numbers of parameters. (I have the rest of the code set up so that everything auto-adjusts depending on how many columns are in the sam...
<p>Try:</p> <pre><code>import inspect def numargs(func): args, varargs, keywords, defaults = inspect.getargspec(func) return len(args) </code></pre> <p>works for a "plain" function <code>func</code> without a <code>*a</code> or <code>**k</code> argument.</p> <p>Then, you can call</p> <pre><code>func(*input...
python|numpy|deap
0
354,263
27,891,546
Use built-in setattr simultaneously with index slicing
<p>A class I am writing requires the use of variable-name attributes storing numpy arrays. I would like to assign values to slices of these arrays. I have been using setattr so that I can leave the attribute name to vary. My attempts to assign values to slices are these:</p> <pre><code>class Dummy(object): def...
<p>Think about how you would normally write this bit of code:</p> <pre><code>d.x[0:3] = [8, 8, 8] # an index operation is really a function call on the given object # eg. the following has the same effect as the above d.x.__setitem__(slice(0, 3, None), [8, 8, 8]) </code></pre> <p>Thus, to do the indexing operating yo...
python|numpy|slice|setattr
3
354,264
27,464,394
Find points in cells through pandas dataframes of coordinates
<p>I have to find which points are inside a grid of square cells, given the points coordinates and the coordinates of the bounds of the cells, through two pandas dataframes. I'm calling <strong>dfc</strong> the dataframe containing the code and the boundary coordinates of the cells (I simplify the problem, in the real...
<p>Probably a better way, but since this has been sitting out there for awhile..</p> <p>Using Pandas boolean indexing to filter the dfc data frame instead of np.where()</p> <pre><code>def findGrid(dfp): c = dfc[(dfp['x'] &gt; dfc['minx']) &amp; (dfp['x'] &lt; dfc['maxx']) &amp; (dfp['y']...
python|pandas|dataframe|points|spatial-query
2
354,265
27,523,022
numpy array directional mean without dimension reduction
<p>How would I do the following:<br> With a 3D numpy array I want to take the mean in one dimension and assign the values back to a 3D array with the same shape, with duplicate values of the means in the direction they were derived...<br> I'm struggling to work out an example in 3D but in 2D (4x4) it would look a bit l...
<p>You can use the <code>keepdims</code> keyword argument to keep that vanishing dimension, e.g.:</p> <pre><code>&gt;&gt;&gt; a = np.random.randint(10, size=(4, 4)).astype(np.double) &gt;&gt;&gt; a array([[ 7., 9., 9., 7.], [ 7., 1., 3., 4.], [ 9., 5., 9., 0.], [ 6., 9., 1., 5.]]) &gt;...
python|arrays|numpy
4
354,266
27,525,375
Python profiling: time spent on each line of function
<p>I have been studying examples from the <a href="https://docs.python.org/2/library/profile.html" rel="noreferrer">profile documentation </a> and I have come to the workflow when I run</p> <pre><code>import cProfile as profile import pstats pr = profile.Profile() pr.runcall(myFunc, args, kwargs) st = pstats.Stats(p...
<p>There is a good package for that on PyPI - <a href="https://pypi.python.org/pypi/line_profiler/" rel="nofollow"><code>line_profiler</code></a></p>
python|numpy|workflow|profile
3
354,267
27,617,901
pandas dataframe taking a long time to put in one row
<p>Everything works, but the last method takes forever (over 1.5 seconds) The dataframe is empty, populated with around 20 columns. The rest of the methods take under .5 seconds. I would think it wouldn't take so long for a pandas dataframe to create a new row with a given index and populate it with fields.</p> <p>An...
<p>Although possible, adding to a dataframe like this isn't a good/efficient way to go. </p> <p>I would create and maintain a dict and then batch convert it to a dataframe like this</p> <pre><code>d = {'A': [1,3,5,2], 'B' : [3,3,7,8]} df = pd.DataFrame(d) df A B 0 1 3 1 3 3 2 5 7 3 2 8 </code>...
python|pandas|flask
2
354,268
27,674,880
Python: Replace a number in array with a string
<p>I have an array of numbers, which I would like to replace with a string depending on some condition. I can replace them with numbers:</p> <pre><code>d_sex = rand(10) d_sex[d_sex &gt; 0.5] = 1 d_sex[d_sex &lt;= 0.5] = 0 d_sex </code></pre> <p>But I cannot do <code>d_sex[d_sex&gt;0.5] = "F"</code>. How would I do th...
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">numpy.where</a> is the equivalent of Julia's <code>ifelse</code>:</p> <pre><code>&gt;&gt;&gt; np.where(d_sex &gt; 0.5, 'M', 'F') array(['F', 'M', 'M', 'F', 'F', 'M', 'F', 'M', 'F', 'F'], dtype='|S1') </code></pre>
python|arrays|numpy
4
354,269
27,890,828
new values appear after numpy concatenate
<p>I load data from netcdf file. Original data contains some values of 1.e+15, which I define as Nan:</p> <pre><code>from netCDF4 import Dataset import numpy as np t = Dataset('temperature.nc', 'r').variables['t'][0] ind = np.where(t==1.E15) t[ind] = np.nan </code></pre> <p>Now I want to shift the data for another l...
<p>You're doing a floating point comparison; 1.00000000001e15 != 1.000000000000e15; so this won't generally work. Use something like <code>np.where(t&gt;=1e15)</code> instead.</p>
python|numpy|split|concatenation
1
354,270
61,392,858
Is there a method to initialise just a part of a vector, then the other one, using numpy.random.randint?
<p>I need to initialise the first 3 elements of my array (indice), with values between 1 and 120, and the next 3 with values between 1 and 140 Here is what i tried</p> <pre><code>import numpy as np indice=np.zeros((1,6)) indice[0:3]=np.random.randint(1,121,3) indice[3:6]=np.random.randint(1,141,3) </code></pre> <p>an...
<p>You can do the following:</p> <pre><code>import numpy as np indices1 = np.random.randint(1,121, (1,3)) indices2 = np.random.randing(1, 141, (1,3)) indices = np.concatenate((indices1, indices2), axis=1) </code></pre>
python|numpy
2
354,271
61,446,975
transfer data from an earlier part of a dataframe to a later part based on criteria match
<p>Ok, I tried to figure this one out but I couldn't do it and I couldn't find any other questions quite like it...</p> <p>Using pandas and a dataframe, I need to match data from an earlier part of a dataframe and put it in a later part of the dataframe, based on a matching value. The data looks like this:</p> <pre><...
<p>You can use <code>apply</code> to find the matching values, then convert them to columns with <code>apply(pd.Series)</code>.</p> <pre><code>s = df['lor'].apply(lambda x: df.loc[df['nc'] == x, ['Date', 'oldval']].values).explode() df[['xdate','xval']] = s.apply(pd.Series) </code></pre>
python|pandas|dataframe
0
354,272
61,253,066
How to replace certain values in pandas Series with its previous value?
<p>I have a pandas Series object <code>s</code> like this:</p> <pre><code>&gt;&gt;&gt; s date 2020-03-26 19.72 2020-03-27 19.75 2020-03-30 19.43 2020-03-31 19.69 2020-04-01 -- 2020-04-06 20.03 2020-04-07 20.45 2020-04-08 21.00 2020-04-09 -- 2020-04-10 20.96 2020-04-13 20.75 2020-...
<p>You could replace those <code>--</code> to <code>NaN</code> and just <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>ffill</code></a>:</p> <pre><code>df.replace('--', float('nan')).ffill() date 2020-03-26 19.72 2020-03-27 ...
python|pandas
1
354,273
61,195,836
Find largest 2 values for each year in the returned pandas groupby object after sorting each group
<p>My dataframe has 3 columns: Year. Leading Cause,Deaths. I want to find the total number of deaths by leading cause in each year. I did the following: <code>totalDeaths_Cause = df.groupby(["Year", "Leading Cause"])["Deaths"].sum()</code> which results in:</p> <p><div class="snippet" data-lang="js" data-hide="false" ...
<p>Let us do </p> <pre><code>df=df.sort_values().groupby(level=0).tail(1) </code></pre>
python|pandas|pandas-groupby
1
354,274
61,368,342
How can I get reproducible results in keras for a convolutional neural network using data augmentation for image classification?
<p>If I train the same convolutional neural network model architecture (on the same data) twice, clearing the session between runs, I get different results. </p> <p><a href="https://i.stack.imgur.com/1chAt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1chAt.png" alt="tensorboard_plot"></a></p> <p...
<p>I've now got reproducible results (with the initial random weights being the same for each experiment and thereby ensuring that any difference in results is due to the differences between experiments rather than due to different initial weights) by:</p> <p>1) Clearing the session and setting the random seeds and tf...
python|tensorflow|keras|random-seed|reproducible-research
1
354,275
61,220,012
Merging two df based on dates if between some range and average the values
<pre><code> df_A start_date end_date 0 2017-03-01 2017-04-20 1 2017-03-20 2017-04-27 2 2017-04-10 2017-05-25 3 2017-04-17 2017-05-22 df_B event_date price 0 2017-03-15 100 1 2017-02-22 200 2 2017-04-30 100 3 2017-05-20 150 4 2017-05-23 150 </code></pre> <p>Result </p> <pre...
<p><a href="https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.conditional_join.html#janitor.conditional_join" rel="nofollow noreferrer">conditional_join</a> from <a href="https://pyjanitor-devs.github.io/pyjanitor/" rel="nofollow noreferrer">pyjanitor</a> may be helpful in the abstraction/c...
python|pandas|dataframe|join|python-3.7
0
354,276
61,428,079
Groupby using pandas the different row data
<p>I have data set as follow:</p> <pre><code>Class Students Seven 10 Seven 15 Five 12 Two 23 Two 36 Ten 16 Ten 10 Ten 5 </code></pre> <p>I need to group them by rows, and make manipulations further:</p> <p>Required output:</p> <pre><code>Class ...
<p>Like this:</p> <pre><code>In [536]: df = df.groupby('Class').sum().reset_index() In [537]: df Out[537]: Class Students 0 Five 12.0 1 Seven 25.0...
python|pandas|dataframe
2
354,277
61,277,279
Pandas Big DataFrame Comparison
<p>I compare record from 2 big Dataframe consist 3 columns (X,Y,Z) and create a Result DataFrame recording paired data where both X's and Y's are close each other (&lt;0.05) It works for small amount of data, unfortunately I have around 33,000-35,000 rows make loop literally endless. Is there any other way to make loop...
<p>I manage to solve this by slicing the DataFrame into 100 smaller portion based on X range value and only compare data within each portion, I don't want to loose any data in between portion so I give 5% overlap in between range and on the top and I will deal with duplication later.</p> <p>It still very slow but at l...
python|pandas|bigdata
0
354,278
61,306,432
First non-null value per group in a table with many columns
<p>The problem of finding first non-null values is discussed extensively on SO, but all the solutions are problematic for some reason, maybe due to my inexperience with PostgreSQL. I have the following structure in the table:</p> <pre><code>group submitted num1 num2 num3 str1 str2 str3 ... 32 14:0...
<p>There is a trick, which is to use <code>array_agg()</code> and remove nulls. That would be:</p> <pre><code>select groupid, (array_remove(array_agg(num1 order by submitted desc), null))[1] as num1, (array_remove(array_agg(num2 order by submitted desc), null))[1] as num2, . . . from t group by g...
sql|pandas|postgresql
3
354,279
61,316,285
How to find any common existing in Pandas Column
<p>I have a DataFrame likes below:</p> <pre><code>IDS Metric 1,2 100 1,3 200 3 300 ... </code></pre> <p>I want to find any two IDs exist in the same row, for example, both "1,2" and "1,3" exist in one row, but "2,3" has no direct relationship (means no competition between them in business)</p> <p>I want to ha...
<p>Use:</p> <pre><code>df["IDS"].str.split(',', expand=True).isin(target_list).all(axis=1).any() </code></pre> <p>Another idea with sets:</p> <pre><code>target_list = ['1', '2'] s = set(target_list) a = any(s.issubset(x.split(',')) for x in df["IDS"]) print (a) True </code></pre> <p><strong>Details</strong>:</p> ...
python|pandas|dataframe
1
354,280
61,418,485
Better Way to do this in Pandas?
<p>I'm just seeking some guidance on how to do this better. I was just doing some basic research to compare Monday's opening and low. The code code returns two lists, one with the returns (Monday's close - open/Monday's open) and a list that's just 1's and 0's to reflect if the return was positive or negate. </p> <p>P...
<p>You can do that by straight forward : </p> <p><code>(history['open']-history['low'])&gt;0</code></p> <p>This will give you <code>true</code> for rows where <code>open</code> is greater and <code>flase</code> where <code>low</code> is greater. </p> <p>And if you want <code>1,0</code>, you can multiply the above st...
python|pandas|dataframe|stock
1
354,281
61,419,057
TFF: How create a Non-IID dataset
<p>I have 2 classes and every class has 140 examples, and I have 4 clients, I would like to create a non-iid dataset like the paper of McMahan, how divide examples into fragments ? </p>
<p>Note: there are many notions of "non-iid-ness" that may be interesting to explore.</p> <ul> <li><p><em>Label non-iid</em>: you might want to make the distribution of labels very unbalanced across clients. Evenly distributing the number of examples, we can still get non-iid distribution such as <code>[(35, 35), (10,...
tensorflow-federated
3
354,282
61,536,949
How to write a simple loop (for element of a matrix) in Tensorflow?
<p>This code is in Matlab2018b + Tensorflow 1.2 (tf) + Numpy (np) </p> <pre><code>%A is a matrix of size [4,10], initialize from the same A_ in Matlab as A = tf.Variable(np.float32(A_)); %Input is a input array of size [1, 10] as Input = tf.placeholder(tf.float32,[10]); %during a loop I pass value to it from Matlab...
<p>you can easily translate the code with <code>numpy</code>:</p> <pre><code>import numpy as np A = np.zeros(shape=(4,10)) Input = np.ones(shape=(1,10)) for j in range(A.shape[0]): tmp = tmp + np.sum( (A[j,:]-Input)**2 ) </code></pre> <p>The output is </p> <pre><code>&gt;&gt;tmp &gt;&gt; 40 </code></pre> <p>I...
matlab|tensorflow
0
354,283
61,430,020
Calculating propensity functions in python
<p>I'm trying to calculate propensity functions in python, using the equation: propensity function = stoch_rate*product of binom(xi, si) where xi is the number of discrete molecules of a particular reactant in a reaction and si is the ratio between reactants in each equation, both stored in matrices. </p> <pre><code>...
<p>You are referencing the values in stead of the indexes in your for loops. Corrected code:</p> <pre><code>def stoch(): popul_num = np.matrix([100, 200, 0, 0]) LHS = np.matrix([[1,1,0,0], [0,0,1,0], [0,0,1,0]]) #--&gt; three rows for 3 different reactions, each row has 4 elements describing the ratio of react...
python|numpy|matrix
0
354,284
61,383,815
Plot multiple columns values against one column
<p>Now I wanted to plot this dataframe in a single plot like as shown below. The EYE_WIDTH variable is combined with combination OF LANE and SLOT_ID. If there is any other way os visualizing this, suggestions are welcome. I tried to plot by just adding plot command ,but all the slot_Ids overlap on each other and inform...
<p>If you are doing what I think you want, then the values on the y-axis seem to be meaningless and you just want to preserve the overall relationship between the values?</p> <p>If that is so, then you can normalize each column so that the values are contained in a defined interval (here <code>[–0.5, 0.5]</code>) and ...
python-3.x|pandas|matplotlib|seaborn
1
354,285
61,380,768
KERAS selects same fraction from each class for validation (for eg. Validation fraction = 0.2)
<p>i have been reading many forums, no clear answer. At many places they say, that it selects the last 20% for our example from the data. Say our data in in two folders Cats and Dogs... so if it were to select only last 20% of the data from Dogs folder and none from cats, wont it be wrong ? . Can keras actually make su...
<p>Does the validation set have to include cats and dogs, if classifying cats and dogs? Yes. What the validation set actually includes depends on how you implement the program, it is not a responsibility of Keras.</p>
tensorflow|image-processing|keras|deep-learning|artificial-intelligence
0
354,286
61,474,514
Remove RELU activation from Resnet model in Pytorch
<p>How to remove all RELU activation layers from Resnet model in pytorch and if possible replace it by a linear activation layer?</p>
<pre><code>model = models.resnet50() names = [] for name, module in model.named_modules(): if hasattr(module, 'relu'): module.relu = nn.Sigmoid() // or nn.Identity() accordingly print(model) </code></pre> <p>This works for either replacing activations or making it identity</p>
python|deep-learning|pytorch
4
354,287
61,264,795
Pandas: UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
<p>community. I want to open a CSV using pandas and perform analysis on it. Please, help as I am not able to open the CSV itself. I tried opening it with UTF-8, Latin-1, and ISO-8859-1 encoding. It didn't work. CODE:</p> <pre><code>csv_file3='COVID-19-geographic-disbtribution-worldwide.csv' with open(csv_file3,'rt')a...
<p>Try this,check this <a href="https://docs.python.org/3/library/codecs.html#standard-encodings" rel="noreferrer">standard encodings</a> as well.</p> <pre><code>data = pd.read_csv("COVID-19-geographic-disbtribution-worldwide.csv", encoding = 'unicode_escape', engine ='python') </code></pre>
pandas|csv|unicode|utf-8|codec
22
354,288
61,342,267
Removing the rows that columns don't match with the same values
<p>I have a data frame that looks like this.</p> <p>This is what I have:</p> <pre><code> V1 V2 V3 hello 0 0 nice 0 1 meeting 1 1 you 1 0 </code></pre> <p>I want to make it look like...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with inverted logic - get all rows with same values in both columns:</p> <pre><code>df = df[df.V2 == df.V3] </code></pre> <p>Alternative with <a href="http...
python|pandas|merge
3
354,289
61,385,244
Shape mismatch when load model in nodejs with @tensorflow/tfjs-node (it's OK in browser with same code)
<p>I have trained a tf.Sequential model and deployed this model to a remote server, it's ok to load the deployed model in browser, but when if i try to load the deployed model from nodejs environment, A strange shape mismatch error occur:</p> <p><em>Error: Based on the provided shape, [98,50], the tensor should have 4...
<p>I managed to fix this by create my own customized IOHandler, still don't understand why node_http handler doesn't work.</p> <pre class="lang-js prettyprint-override"><code> import * as tf from '@tensorflow/tfjs'; import axios from 'axios'; import url from 'url'; /** * Convert a Buffer or an Array of Buffers to an...
node.js|tensorflow
0
354,290
61,410,382
Replace multiple values based on multiple conditions
<p>I want to replace two values from two different columns with another two values from two different columns. Example:</p> <p>I want to replace all values that are <code>null</code> in column <code>value</code> where the value in column <code>variable</code> is <code>name</code> and the <code>source</code> is <code>a...
<p>If I understood well, this is a solution :</p> <pre><code>df[(df['variable'] =!'name') | (~df['value'].isna()) | (df['source'] =! 'a')] </code></pre>
python|pandas
0
354,291
61,559,259
How to annotate a histogram in matplotlib with a bracket
<p>I want to place a bracket over a fraction of my data in a histogram to appear similar to the figure below. Can anyone show me how to do this with my code?</p> <p><a href="https://i.stack.imgur.com/ZHH8T.png" rel="nofollow noreferrer">Age demographic sizes in the UK population</a></p> <pre><code>import pandas as pd...
<p><code>max(pop[-4:])</code> calculates the vertical position to start the bracket as the maximum of the bars involved. With adequate <code>x</code> and <code>y</code> coordinates the full bracket can be drawn.</p> <p>The average of the bar positions can be used as x-coordinate for the text.</p> <pre class="lang-py ...
python|pandas|matplotlib
1
354,292
61,322,077
Easiest way to replace row values by another dataframe in pandas?
<p>I'm new in python and I prefer to use R.</p> <p>I want to replace specific rows by other dataframe, so what I do is the following:</p> <h1>My code</h1> <pre><code>xgb=pd.DataFrame([[0, 0, 0]]*18,columns=[&quot;0&quot;,&quot;1&quot;,&quot;2&quot;]) xgb.iloc[8:12,:]=pd.DataFrame([[0.36950416, 0.08233581, 0.54816002]]*...
<p>Simpliest is set by list (with same length like columns):</p> <pre><code>xgb=pd.DataFrame([[0, 0, 0]]*18,columns=["0","1","2"]) xgb.iloc[8:12,:]=[0.36950416, 0.08233581, 0.54816002] print (xgb) 0 1 2 0 0.000000 0.000000 0.00000 1 0.000000 0.000000 0.00000 2 0.000000 0.000000 0....
python|pandas
0
354,293
61,188,682
Pandas resample creates new dates not in index when converting daily data to monthly data
<pre><code>import yfinance as yf import pandas as pd data = yf.download('SPY', start='2017-12-31', end='2019-12-31') df = data[['Adj Close']] df.resample('2Q',closed='left').mean() </code></pre> <p>The output from resample shows quarter-end dates 30-06-2018, 31-12-2018, 30-06-2019 and 31-12-2019. But some of tho...
<p>a) <code>df.resample('2Q', closed='left').mean()</code> gives</p> <pre><code> Adj Close Date 2018-06-30 260.626654 2018-12-31 268.594670 2019-06-30 273.702913 2019-12-31 297.780020 </code></pre> <p>which is equivalent to</p> <pre><code>pd.DataFrame({'Date': ['2018-06-30', '2018-1...
python|pandas|finance
0
354,294
61,228,803
how to plot many columns of Pandas data frame
<p>I need to make scatter plots using Boston Housing Dataset. I want to plot all the other columns with MEDV column. This code makes all plot on the same graph. How can I separate them?<a href="https://i.stack.imgur.com/iUPvy.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>import matplot...
<p>Your code will work if you flatten the <code>axes</code> object because currently you are looping once over <code>axes</code> which is a 2-d object. So use <code>axes.flatten()</code> in the for loop and then use <code>ax.scatter</code> which will plot each column to a new figure. </p> <p>The order of plotting will...
python|pandas|matplotlib|scatter-plot|subplot
2
354,295
61,481,921
How to set and track weight decays?
<p>What is a guideline for setting weight decays (e.g. l2 penalty) - and mainly, how do I <em>track</em> whether it's "working" throughout training? (i.e. whether weights are actually decaying, and <em>by how much</em>, compared to no l2-penalty).</p>
<p>A common approach is &quot;try a range of values, see what works&quot; - but its pitfall is a lack of <em>orthogonality</em>; <code>l2=2e-4</code> may work best in a network <em>X</em>, but not network <em>Y</em>. A workaround is to guide weight decays in a <em>subnetwork</em> manner: (1) group layers (e.g. <code>Co...
python|tensorflow|keras|deep-learning
5
354,296
61,299,881
expected lstm_1_input to have 3 dimensions, but got array with shape (0, 1)
<p>I am trying to analyze sales data. My excel is shaped 8 column headings (Week ending date, Monday, Tuesday, ...., Sunday) with sales data. The aim is to study hostoric sales and predict upcoming sales. </p> <pre><code>import numpy as np from pandas import read_csv from keras.models import Sequential from keras.laye...
<p>There are two approaches when feeding inputs on your model:</p> <p>1st option: using the <strong>input_shape</strong></p> <pre><code>model.add(Dense(300, activation='relu', input_shape=(6, 1))) </code></pre> <p>Here the input shape is in <strong>2D</strong>, but you should feed your network a <strong>3D</strong> ...
python|tensorflow|model
0
354,297
61,542,976
Returning a tuple from a pandas series
<p>I have a pandas series which is as follows:</p> <pre><code>series = pd.Series([100, 70, 50], index = ['Brazil', 'France', 'UK']) </code></pre> <p>I want to retrieve a tuple from the first row with the label as a string and 100,</p> <pre><code>('Brazil', 100) </code></pre> <p>It's similar to <a href="https://stac...
<p>Convert <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.items.html" rel="nofollow noreferrer"><code>Series.items</code></a> to list:</p> <pre><code>print (list(series.items())) [('Brazil', 100), ('France', 70), ('UK', 50)] </code></pre>
python|pandas
0
354,298
61,301,439
Multiply string and integer columns
<p>I have a DataFrame with such a structure[1] and i want to multiply the string and integer columns.</p> <pre><code>+----------------------+------------+-------------------------+-----------+--+ | url | date | word | mentioned | | |----------------------+------------+-------...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>explode</code></a> and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.repeat.html" rel="nofollow noreferrer"><code>series.repeat</code></a> , ...
python|pandas|dataframe
3
354,299
61,374,929
Pandas append series from tuple into empty dataframe
<p>I'm trying to split a dataframe with a certain logic.</p> <p>Here's my attempt:</p> <pre><code>def split_df(df: pd.DataFrame): train = pd.DataFrame(columns = df.columns) valid = pd.DataFrame(columns = df.columns) i = 0 for data in tqdm(df.iterrows()): if i &gt; 10: break ...
<p>Append does not modify the dataframe in place, so you need to reassign your variable to keep changes:</p> <pre><code>train = train.append(tmp,ignore_index=True) valid = valid.append(tmp,ignore_index=True) </code></pre>
python|pandas
1