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
358,800
56,979,265
Timestamp with timezone column in Pandas
<p>I am reading data from a Java source. I end up with the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df.head() open timestamp 0 1.13550 2019-02-24T17:00-06:00[US/Central] 1 1.13570 2019-02-24T17:05-06:00[US/Central] 2 1.13560 2019-02-24T17:10-06:00[US/Centra...
<p>You can try remove the <code>[...]</code> part, then pass it to <code>to_datetime</code>:</p> <pre><code>pd.to_datetime(df.timestamp.str.extract('(.*)\[.*\]')[0]) </code></pre> <p>returns:</p> <pre><code>0 2019-02-24 17:00:00-06:00 1 2019-02-24 17:05:00-06:00 2 2019-02-24 17:10:00-06:00 3 2019-02-24 17:15...
python|pandas|datetime|timezone
1
358,801
57,243,100
Saving txt file from TextInput and then re loading it in separate Window/Class Kivy
<p>Trying to create a basic version of the website "leafly". I want use user input to look up a row in a data set and display all the information on whatever the user has typed in.</p> <p>I save the user's TextInput to a txt file and then open the text file in the next window. The txt file saves fine but for some reas...
<p>You read the text file in the class definition of <code>ThirdWindow</code> which happens at startup, if you want it to happen when you enter the screen, you can put this code in the <code>on_pre_enter</code> (or <code>on_enter</code> but this will happen after the transition has complete, so if it changes the conten...
python|pandas|kivy|kivy-language
0
358,802
57,076,913
Pandas, Apply Function to Data Frame That Returns One to Many Rows
<p>I have a pandas dataframe that I need to apply a function to. The function however, returns many items for a single row in the dataframe. I would like to create a new dataframe with the values returned from the function. So, far when I applied the function, the new dataframe had the same number of rows as the origin...
<p>I'm not sure what your data looks like, but here is a way to do it efficiently :</p> <pre><code>df = pd.DataFrame({'id' : [0,1,2,3,4,5,6]}) flattened_list = ["{}_{}".format(x, i) for i in range(4) for x in df['id']] df2 = pd.DataFrame(flattened_list) </code></pre> <hr> <p>Output <code>flattened_list</code>:</p>...
python|pandas|python-2.7|numpy
2
358,803
57,186,672
Why this Python pandas DataFrame code does not work?
<p>My code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns income_vs_hardship = %sql SELECT per_capita_income_, hardship_index FROM chicago_socioeconomic_data; plot = sns.jointplot(x='per_capita_income_',y='hardship_index', data=pd.DataFrame(income_vs_hards...
<p><code>DataFrame</code> is a class of the pandas module, not a method that you can apply to a DataFrame instance. </p> <p><code>income_vs_hardship.DataFrame()</code> can't be interpreted by Python, as <code>income_vs_hardship</code> has no <code>DataFrame</code> method. Instead, <code>pd.DataFrame(income_vs_hardship...
python|pandas|seaborn
0
358,804
56,954,513
Export keras model to tf savedModel format: how to fix serving_input_fn
<p>I want to leverage google's AI-platform to deploy my keras model, which requires the model to be in a tensorflow SavedModel format. I am saving a keras model to a tensorflow estimator model, and then exporting this estimator model. I run into issues in defining my <code>serving_input_receiver_fn</code>.</p> <p>Here...
<p>I've managed to save a Keras model and host it using TF Serving using the <a href="https://www.tensorflow.org/api_docs/python/tf/saved_model/Builder" rel="nofollow noreferrer"><code>tf.saved_model.Builder()</code></a> object. I'm not sure if this can be easily generalized to your application, but below is what worke...
tensorflow|google-cloud-ml|tf.keras|gcp-ai-platform-notebook
1
358,805
57,254,222
Transposing values in a column of a Pandas data frame
<p>I want to create a data frame containing the values of the 'atoms' column in df1 transposed, so that the resulting data frame looks like df2.</p> <h3>df1:</h3> <pre><code> name atoms 0 CH4 C 1 CH4 H 2 CH4 H 3 CH4 H 4 CH4 H 5 NH3 N 6 NH3 H 7 NH3 H 8 NH3 H ...
<p>This is mostly a <code>crosstab</code>, but with a couple additional steps.</p> <pre><code>u = df.assign(key=df.groupby('name').cumcount()).set_index('name') i = pd.crosstab(u.index, u['key'], u['atoms'], aggfunc='first') # Cleanup and formatting i.reindex(u.index).add_prefix('a').rename_axis(None, axis=1).reset_...
python|pandas
1
358,806
56,976,313
FileNotFoundError: [Errno 2] No such file or directory: with csvreader
<p>I want a CSV file to be read using csvreader on Google Colaboratory to emulate a research paper results. But I am getting the following error:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory: 'wind.csv'</p> </blockquote> <p>I have gone through a few articles suggesting how to import a ...
<pre><code>df = pd.read_csv('C:/Users/WELCOME/Desktop/zomato.csv',encoding=&quot;ISO-8859-1&quot;) </code></pre> <p><strong>Instead of</strong></p> <pre><code>df = pd.read_csv('zomato.csv',encoding=&quot;ISO-8859-1&quot;) </code></pre> <p><strong>Sometimes error occurs because of Back slash (\) that is default use must...
python|tensorflow|google-colaboratory
1
358,807
57,267,300
How to erase the last line from CSV file
<p>I've been importing CSVs using pandas, but I keep getting a random extra line every time I try to use it and it causes errors in my code. How do I completely erase this line?</p> <p>The code I used to import it was: import itertools import copy import networkx as nx import pandas as pd import ma...
<p>You could try to select the column valid elements this way: <code>drop[bool(drop.&lt;column_name&gt;[1]) == True]</code>. I use the bool cast on the 2nd element of the set, because an empty dict <a href="https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work">casted...
python|pandas|csv|export-to-csv
0
358,808
56,918,842
getting microseconds become zero in pandas
<p>I want to use 'diff()' to get the difference of two consecutive time data in microseconds. </p> <p>But for some data, when the difference is 1 second. I got some problems, which are shown in the following code:</p> <pre><code>df = pd.DataFrame({'time':['2019-06-10 16:37:16.319', '2019-06-10 16:37:17.319']}) df['ti...
<p>There's a nuance. The <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timedeltas.html#attributes" rel="nofollow noreferrer">Timestamp attributes</a> "access various components of the Timedelta or TimedeltaIndex", they do not convert to that specific frequency. The attributes are defined up to the ne...
python|pandas
2
358,809
56,942,937
Pandas - Row number since last greater than 0 value
<p>Let's say I have a Pandas series like so:</p> <pre><code>import pandas as pd pd.Series([1, 0, 0, 1, 0, 0, 0], name='series') </code></pre> <p>How would I add a column with a row count since the last >0 number, like so:</p> <pre><code>pd.DataFrame({ 'series': [1, 0, 0, 1, 0, 0, 0], 'row_num': [0, 1, 2, 0,...
<p>Try this:</p> <pre><code>s.groupby(s.cumsum()).cumcount() </code></pre> <p>Output:</p> <pre><code>0 0 1 1 2 2 3 0 4 1 5 2 6 3 dtype: int64 </code></pre>
python|pandas|indexing
7
358,810
56,880,471
Calculate travel time in pandas
<p>I am a beginner in python. I have a huge <code>dataframe</code>. The data looks like this:</p> <pre><code>df ID Annotation Time A Boarding 7:20:00 A Alighting 8:30:50 B Boarding 13:45:00 B Alighting 14:00:05 C Boarding 17:05:00 C Alighting 17:15:00 </code></pre> <p>I want to calculate...
<p>A solution without pivot:</p> <pre><code>&gt;&gt;&gt; df2 = pd.DataFrame({'Time %s' % i: pd.to_datetime(pd.Series(x.values.ravel())) for i, x in df.iloc[:, 1:].set_index('Annotation').T.groupby(level=0, axis=1)}) &gt;&gt;&gt; df2['ID'] = df['ID'].unique() &gt;&gt;&gt; df2['Travel Time (Minutes...
python|pandas
1
358,811
56,974,397
how to allocate one variable to two columns of a txt file
<p>I have a txt file which contain Timestamp columns. My file is like below: I need to read the file and allocate one variable for the Timestamp like this: t= 2014-08-26 19:49:32, which contain two columns of my file. I can make them as a string with code below, but the problem is that I need it to be as a Timestamp. S...
<p>To convert a date string to a timestamp:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import time &gt;&gt;&gt; import datetime &gt;&gt;&gt; s = "2014-08-26 19:49:32" &gt;&gt;&gt; time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S").timetuple()) 1409107772.0 </code></pre>
python|pandas
1
358,812
56,925,570
Does iloc[ :, 1:2 ]. values and .iloc[ :, 1].values work differently?
<p>If I slice a <code>pandas dataframe</code> with <code>dataset.iloc[:, 1:2].values</code>, it's giving me a <code>2 dimensional(matrix)</code> structured data where <code>dataset.iloc[:, 1].values</code> is giving me <code>1 dimensional</code> data. So, my doubt is <code>iloc[:,1:2]</code> &amp; <code>iloc[:,1]</code...
<p><code>df.iloc[:, 1:2]</code> returns a dataframe (matrix) whereas <code>df.iloc[:, 1]</code> returns a series (vector). A vector does not have column size. Try this if you want to keep the dataframe structure</p> <pre><code>df.iloc[:,[1]] </code></pre>
python|python-3.x|pandas|numpy|numpy-ndarray
4
358,813
57,006,860
How can I count how many male/female are in each title?
<p>I am a newbie to datascience and I want to count how many female/male are in each Title.</p> <p>I tried the following piece of code:</p> <p>'''</p> <pre><code>newdf = pd.DataFrame() newdf[ 'Title' ] = full[ 'Name' ].map( lambda name: name.split( ',' ) [1].split( '.' )[0].strip() ) newdf['Age'] = full['Age'] newdf['...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> for aggregate <code>mean</code> with <code>size</code> and for new columns add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas....
python|pandas|dataframe|pandas-groupby
1
358,814
56,919,342
How to find the row of a dataframe from column value then update row with dictionary?
<p>I have a dataframe of the form:</p> <pre><code>import pandas as pd df = pd.DataFrame(None,columns= ['Name','Age','Asset']) df = df.append({'Name':'John','Age':10,'Asset':'Bike'},ignore_index=True) df = df.append({'Name':'Sarah','Age':17,'Asset':'Laptop'},ignore_index=True) df = df.append({'Name':'Noah','Age':14,'As...
<p>I think you are trying to make the changes to more than just John? But for any dictionary? </p> <p>Let's set the dictionary you provided as</p> <pre><code>di = {'Name' :'John','Age':11,'Asset' :'Phone'} </code></pre> <p>Then we can filter using .loc rows by 'Name', and select columns 'Age' and 'Asset', then set v...
python-3.x|pandas|dataframe|dictionary
1
358,815
57,131,464
Find certain value of numpy ndarray
<pre><code>a = np.array([[1,2,3][4,5,6][7,8,9]]) b = [0,1] </code></pre> <p>I want to find value of <code>a</code> that has <code>(0,1)</code> index which is 2 in this case.</p> <p>I have tried <code>a[b]</code> but it does not show the expected result.</p> <p>How can I solve this problem?</p>
<p>Use <code>a[tuple(b)]</code>, like so:</p> <pre><code>In [3]: a=np.array([[1,2,3],[4,5,6],[7,8,9]]) In [4]: b=np.array([0,1]) In [5]: a[tuple(b)] Out[5]: 2 </code></pre> <p>For more info, see <a href="https://docs.scipy.org/doc/numpy-1.16.0/user/basics.indexing.html#dealing-with-variable-numbers-of-indices-withi...
python|numpy
2
358,816
57,191,697
Pandas - Multiline plot
<p>My data frame is composed by 3 elements: Name, Date and Weight.</p> <p>I would like to plot a line graph where the X axis is the date, the Y is the COUNT OF weights (how many times a give subject weighted himself throughout the day) and each line is a different name.</p> <p>In order to do that, i gave it a shot:</...
<p>One way is to just loop through the names and plot each individually</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(12, 18)) for name, group in data.groupby('name'): group.date.value_counts().plot(ax=ax, label=name) plt.legend() plt.show() ...
python|pandas|pandas-groupby
2
358,817
57,260,961
Pandas Dataframe to a JSON Hierarchy
<p>I have a pandas dataframe as following: </p> <pre><code>tree nodes classes cues directions thresholds exits 1 1 4 i;i;n;i PLC2hrOGTT;Age;BMI;TimesPregnant &gt;;&gt;;&gt;;&gt; 126;29;29.7;6 1;0;1;0.5 2 2 3 i;i;n PLC2hrOGTT;Age;BMI &gt;;&gt;;&gt; 126;29;29.7 0;1;0.5 3 3 4 i;i;n;i...
<p>You will need to work with your data more. You will need to split up ["cues", "exits", "directions", "thresholds"] into 4 columns each. Then you can use groupby to work with (what I assume will then be) "cues0" and so on. Once you have your groupby the way you want, take a look at this awesome code <code>https://...
python|json|pandas
0
358,818
57,273,045
Pandas nested groupby gives unexpected results
<p>I am working on a problem where I am using a nested groupby.apply on a pandas DataFrame. During the first apply I am adding a column that I am using for the second inner groupby.apply. The combined result looks faulty to me. Can anyone explain to me why the below phenomen happens and how to reliably fix it?</p> <p>...
<p>[Mac, Python: 3.6.8]</p> <p>My thinking is that the expected behaviour of nested <code>DataFrame.apply</code>s are going to be a little convoluted to debug. My recommendation is to cut-to-the-chase by emulating what you want to achieve from <code>apply</code> (i.e. map then reduce):</p> <ol> <li>Map: Use python's ...
python|pandas|pandas-groupby
1
358,819
56,881,035
How to create multiple empty dataframes?
<p>Instead of doing:</p> <pre><code>a=pd.DataFrame() d=pd.DataFrame() c=pd.DataFrame() d=pd.DataFrame() e=pd.DataFrame() </code></pre> <p>each at a time. Is there a quick way to initialize all variables with empty dataframe? Because eventually I want to use for loop to assign dataframe values to </p> <pre><code>...
<p>Let's say you have to make <code>n</code> empty dataframes and put it in a list, you can do something like this with the help of list comprehension.</p> <pre><code>n = 10 df_list = [pd.DataFrame() for x in range(n)] </code></pre> <p>You can do similar with a <code>dict</code> so that you can make use of non int k...
python|pandas|dataframe
2
358,820
57,275,559
Transforming/pivoting a DataFrame Instance
<p>I have the following pandas data frame:</p> <pre><code>import pandas as pd data = dict(store=['A', 'B', 'B'], color=['red', 'black', 'black'], size=['small', 'medium', 'small'], quantity=[2, 4, 1]) df = pd.DataFrame(data) </code></pre> <p>which looks like this:</p> <pre><code> store color size quantity 0 ...
<p>You can use <code>melt</code> and <code>pivot_table()</code>:</p> <pre><code>m=df.melt(['store','quantity']) </code></pre> <hr> <pre><code>m.pivot_table(index='value',columns='store',values='quantity',aggfunc='sum',fill_value=0) </code></pre> <hr> <pre><code>store A B value black 0 5 medium 0 4 r...
python|pandas|pivot|transform
2
358,821
56,947,186
'<=' not supported between instances of 'str' and 'int'
<p>Following is my code of reading a CSV file but got error what's wrong with my code.</p> <pre><code>df2 = pd.read_csv(img_category_path, delim_whitespace= True, header=0, names=['category'], low_memory=False ) df['upper_lower'] = ['1' if i &lt; 21 else '3' if i &gt; 36 else '2' for i in df2['category']] </co...
<p>You can solve your issue by changing:</p> <pre><code>df['upper_lower'] = ['1' if i &lt; 21 else '3' if i &gt; 36 else '2' for i in df2['category']] </code></pre> <p>to:</p> <pre><code>df['upper_lower'] = ['1' if int(i) &lt; 21 else '3' if int(i) &gt; 36 else '2' for i in df2['category']] </code></pre> <p...
python|python-3.x|pandas
2
358,822
56,927,370
Python function to change data type of a column not working
<p>I wrote a python function to take in a column of a dataframe, check the data type and if it's false change to required data type. However, the changes happen only within the function. How to fix this to make permanent changes to the dataframe?</p> <pre><code>def change_required_data_type (column,data_type): is_...
<p>For your question of something only working inside a function and not outside, you need to add <strong>return some object</strong> to the end of your function.</p> <pre><code>def myfunc(column, data_type): # ... elif is_correct == False: column = column.astype(data_type) print('False') ...
python|pandas
0
358,823
57,193,926
DataFrame.values on selected column
<p>I have the following error when i try to get not all values but only specified column. I think the error comes from the column I specify after <code>.values</code> Any help would be appreciated. </p> <p><code>supp_bal</code> dataframe:</p> <pre><code> circulating_supply total_supply currency ...
<p>Do you mean by:</p> <pre><code>f = pos_bal.index.get_level_values('currency') supp_bal['circulating_supply'].loc[f] </code></pre>
python|pandas
0
358,824
57,137,604
Updating a variable to the value of a string only returns the first character of the string
<p>I'm trying to hard code the major ticks for a plot by creating an array which I will then attach to the x-axis of the graph. However, I can't get the array to come out correctly. I created an empty list <code>xticks</code> which I want to update every 5th value the correct value from <code>major_ticks</code> but the...
<p>This happens because <code>np.full</code> doesn't generate an array of strings in the first place but an array of chars:</p> <pre><code>np.full(length_x,'',dtype=str).dtype dtype('&lt;U1') </code></pre> <p>Typically I wouldn't recommend to use <code>numpy</code> for string operations. Replacing <code>xticks=np.ful...
python|python-2.7|list|numpy|numpy-ndarray
2
358,825
57,085,118
Equivalent matlab function mod in numpy or python
<p>I was converting some codes from Matlab to Python.</p> <p>In matlab there is the function <code>mod</code> which gives the modulo operation.</p> <p>For example the following example shows different results between the matlab <code>mod</code> and the equivalent numpy <code>remainder</code> operation:</p> <p>Matlab...
<p>This is the core of the problem, in python:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; 6/0.05 == 120 True &gt;&gt;&gt; 6//0.05 == 120 # this is 119 instead False </code></pre> <p>The floating-point result of <code>6/0.05</code> is close enough to 120 (i.e. within the resolution of doubl...
python|matlab|numpy|floating-point
6
358,826
56,915,567
Keras vs PyTorch LSTM different results
<p>Trying to get similar results on same dataset with Keras and PyTorch.</p> <h3>Data</h3> <pre class="lang-py prettyprint-override"><code>from numpy import array from numpy import hstack from sklearn.model_selection import train_test_split # split a multivariate sequence into samples def split_sequences(sequence...
<p>I know it is almost one year too late. But I came across the same problem and I think the problem is the following. From the keras documentation it says:</p> <blockquote> <p>return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence.</p> </blockquote> <p>this basi...
python|keras|pytorch|lstm
8
358,827
57,104,746
Percentage of each day where sum is the total of each day value
<p>I am trying to get the percentage of each day where sum is given.</p> <p>I have data in daily with datetime index and i resemble index to yearly using method sum and here is the code.</p> <pre><code>data_converted = data.resample('AS').sum() </code></pre> <p>and what I want is to get the percentage of each day:</p>...
<p>you may use <code>transform</code> with <code>resample</code> and doing calculation between daily values with result from <code>transform</code> of <code>sum</code></p> <p>Your Sample data: (I just grab partial data which you posted)</p> <pre><code>Out[11]: val dates 1986-01-02 25.56 1986-01-03 26....
python|pandas|dataframe|datetime
3
358,828
56,871,633
Sorting values for every level 1 in pandas multiindex
<p>I'm having a dataframe with multiindex, the first level is an company_ID and the second level is a timestamp. How can I get a rank of all companies depending on their scores, every month?</p> <pre><code> Score company_idx timestamp 10006 2010-01-31 69.875394 201...
<p>You should swap the index levels to have the month first, then sort by timestamp ascending and Score descending:</p> <pre><code>df.index = df.index.swaplevel() df.sort_values(['timestamp', 'Score'], ascending=[True, False], inplace=True) </code></pre> <p>It does not give interesting result with your sample value, ...
python|pandas|sorting|dataframe
2
358,829
57,082,596
Count Number of cycles in graph/ plot using Python / Pandas / Numpy
<p>How can I find out how many times the Y value (Speed) ramps up and down from 700 -800 RPM to 1600 to 1800 RPM and vice versa from graph plotted in matplotlib by using python / pandas / numpy libraries. I have plotted this graph using matplotlib and using dataframe.</p> <p>Expected output should be---> Number of Ra...
<p>Here is a vectorized solution:</p> <pre><code>import pandas as pd df = pd.DataFrame({'speed': [0,1600,0,1600,1600,1600,0,0,0]}) # Check if values are above or below a threshold threshold = 1500 df['over_threshold'] = df['speed'] &gt; threshold # Compare to the previous row # If over_threshold has changed, # the...
python|pandas|numpy|dataframe|matplotlib
3
358,830
56,972,811
Remove outliers from pandas with different types
<p>Currently working on a regression problem, I'm facing some issues in the performance of models. In order to have 'maybe' a better performance, I've some outliers that I'd like to remove.</p> <p>Problem: Remove outliers from a dataframe containing different types.</p> <p>The DF looks like:</p> <pre><code> df.dty...
<p>First of all, I assume that your data distribution is Normal. Here is a great strategy for removing outliers.</p> <ol> <li>Make a Pandas Dataframe with all numeric features, which has outliers.</li> <li><p>Use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel=...
pandas|jupyter-notebook|numeric|categorical-data|outliers
0
358,831
56,883,137
Problems with long lists as input of set_xticklabels (Misaligned)
<p>I am following the NMT with attention (<a href="https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/eager/python/examples/nmt_with_att...
<p>The problem is that you are only setting the tick-labels without specifying the positions of the ticks. Whenever you modify the tick labels, you should <em>always</em> first set the tick positions. So, do the following in your code</p> <pre><code>ax.set_xticks(range(len(sentence))) ax.set_yticks(range(len(predicted...
python|tensorflow|matplotlib
0
358,832
56,924,665
Why does this neural network model work poorly?
<p>I'm trying to create a convolutional neural network, but for some reason after training it is absolutely useless.</p> <p>She always gives such results. <em>unknown</em> (score = 1.00000) test (score = 0.00000)</p> <p>Maybe I built the model wrong.</p> <p>I would like to know. What I am doing wrong? Thanks.</p> <...
<p>This seems to be the case of Overfitting. You can</p> <ol> <li><p><code>Shuffle</code> the <code>Data</code>, by using <code>shuffle=True</code> in <code>cnn_model.fit</code>. Code is shown below:</p> <p><code>history = cnn_model.fit(x = X_train_reshaped, y = y_train, ...
python|tensorflow|neural-network|conv-neural-network
0
358,833
57,152,892
How to create many columns in Pandas (as with a loop in Stata)?
<p>I'm trying to replicate this Stata loop in Pandas:</p> <pre><code>forvalues i = 1/6 { gen int codeL`i' = L`i'.location_level_2 gen int codeF`i' = F`i'.location_level_2 } </code></pre> <p>As you can see, I want to create these new columns: codeL1 code L2...and so on, until I get codeL6, based on the...
<p>You are very close to a working solution! Here's one that follows the suggestion in the comment by @ALollz:</p> <pre><code>for i in range(1, 7): df[f'codeL{i}'] = df['location_level_2'].shift(i) df[f'codeF{i}'] = df['location_level_2'].shift(-i) </code></pre> <p>Note that the structure <code>f'codeL{i}</co...
python|pandas|stata
2
358,834
57,142,564
problem of saving a large panda data frame to pickle or json?
<p>I tried to save a large panda dataframe to JSON file</p> <p>[<img src="https://i.stack.imgur.com/spRb8.png" alt="data[1]"></p> <p>I used these ways</p> <pre><code>df.to_pickle("dfSentsOB.pkl") </code></pre> <p>Unfortunately, I faced with this error, can anyone know what is the reason?</p> <p>but it says:</p> <...
<p>This code can read you csv and give you JSON object. For more <a href="http://geeksforgeeks.org/python-pandas-dataframe-to_dict" rel="nofollow noreferrer">details</a>. You can use python <code>csv</code> and <code>json</code> library then you do not need to use any other library like <code>pandas</code> or <code>mpu...
json|pandas|pickle
1
358,835
45,824,899
Tensorflow unreused Variable Scope
<p>I write codes like below, but I'm not sure whether these fully-connected layers share same variables or not.</p> <pre><code>with tf.variable_scope("loss"): _loss= tf.map_fn(lambda x: tf.contrib.layers.fully_connected(x, output_size), x_list) </code></pre>
<blockquote> <p>whether these fully-connected layers share same variables or not?</p> </blockquote> <p><a href="https://www.tensorflow.org/api_docs/python/tf/map_fn" rel="nofollow noreferrer"><code>tf.map_fn</code></a> op behaves similarly as python native <code>map</code> function. So here all the elements of the l...
tensorflow
0
358,836
45,959,488
select rows with the same data from pandas dataframe
<p>I have a pandas dataframe df</p> <pre><code>df StartDate EndDate Value \ 0 2015-03-25 12:25:43.999994 2015-03-25 13:23:43.979992 0 1 2015-03-25 13:23:43.999998 2015-03-25 13:24:43.979998 1 2 2015-03-25 13:24:43.999994 2015-03-25 13:25:43.979995 0 3 2015-03-26 13:25:...
<p>I think the best is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>date</code></a>s and apply...
python|pandas|datetime|dataframe
3
358,837
46,037,627
tensorflow.contrib.learn.DNNclassifier missing 1 required positional argument: 'feature_columns'
<p>I'm using jupyter notebook to write a deep neural network code. I've encountered this problem when trying to create a DNNClassifier.</p> <pre><code>import tensorflow.contrib.learn as learn classifier = learn.DNNClassifier(hidden_units=[10, 20, 10], n_classes=2) -----------------------------------------------------...
<p>You need to pass correct arguments <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/learn/DNNClassifier" rel="nofollow noreferrer"><code>tf.contrib.learn.DNNClassifier</code></a>, here you didn't pass<code>feature_columns</code> argument. </p> <p>For example, you can use <code>real_valued_column</code...
python-3.x|machine-learning|tensorflow|deep-learning
4
358,838
45,771,809
How to extract and visualize data from OSM file in Python
<p>I have downloaded an OpenStreetMap file on my desktop , and I have used my OSM file in the jupyter notebook. </p> <p><strong>My code:</strong></p> <pre><code>import xml.etree.cElementTree as ET osm_file = "ahmedabad_india.osm" for event, elem in ET.iterparse(osm_file, events=("start",)): print(elem) # p...
<p>You can extract all the data from an <code>.osm</code> file through <strong><a href="http://osmcode.org/pyosmium/" rel="noreferrer">PyOsmium</a></strong> (A fast and flexible C++ library for working with OpenStreetMap data) and then handle it with <strong><a href="http://pandas.pydata.org/" rel="noreferrer">Pandas</...
python|pandas|openstreetmap|osmium
18
358,839
45,993,872
How to use argmax tensorflow function in 3d array?
<p>I want to know how to use <code>tf.argmax</code> in 3D array.</p> <p>My input data is like that:</p> <pre><code>[[[0, -1, 5, 2, 1], [2, 2, 3, 2, 5], [6, 1, 2, 4, -1]], [[-1, -2, 3, 2, 1], [0, 3, 2, 7, -1], [-1, 5, 2, 1, 3]]] </code></pre> <p>And I want to get the output of argmax by this input data like this:</p...
<p>You can use <code>tf.argmax</code> along <code>axis=3</code></p> <pre><code>a = tf.constant([[[0, -1, 5, 2, 1], [2, 2, 3, 2, 5], [6, 1, 2, 4, -1]], [[-1, -2, 3, 2, 1], [0, 3, 2, 7, -1], [-1, 5, 2, 1, 3]]]) b = tf.argmax(a, axis=2) </code></pre>
python|tensorflow|softmax|argmax
0
358,840
46,024,279
TypeError: unhashable type: 'Int64Index'
<p>The section of my code that is causing me problems is </p> <pre><code>def Half_Increase(self): self.keg_count=summer17.iloc[self.result_rows,2].values[0] self.keg_count +=1 summer17[self.result_rows,2] = self.keg_count print(keg_count) </code></pre> <p>So this function is to be executed when a butt...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a>:</p> <pre><code>summer17.iloc[result_rows,2] += 1 </code></pre> <p>Sample:</p> <pre><code>summer17 = pd.DataFrame({'a':[1,2,3], 'b':[...
python-3.x|pandas
2
358,841
46,053,363
Tensorflow MNIST label placeholder shape mismatches errors
<p>I have written following code for MNIST classification training, when I run it throws <code>placeholder</code> shape mismatches errors. </p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=False) x = tf.placeholder(tf.float32, [None, 784...
<p>Change the line</p> <pre><code>mnist = input_data.read_data_sets("/tmp/data/", one_hot=False) </code></pre> <p>to</p> <pre><code>mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) </code></pre>
python|tensorflow
0
358,842
45,828,616
Streaming large training and test files into Tensorflow's DNNClassifier
<p>I have a huge training CSV file (709M) and a large testing CSV file (125M) that I want to send into a <code>DNNClassifier</code> in the context of using the high-level Tensorflow API.</p> <p>It appears that the <code>input_fn</code> param accepted by <code>fit</code> and <code>evaluate</code> must hold all feature ...
<p>Check out the <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/data" rel="noreferrer"><code>tf.data.Dataset</code></a> API. There are a number of ways to create a dataset. I'll outline four - but you'll only have to implement one.</p> <p>I assume each row of your <code>csv</code> files is <cod...
python|csv|tensorflow
35
358,843
45,811,716
How to make input pipeline using tf.RandomShuffleQueue and tf.train.shuffle_batch in tensorflow?
<p>While studying deeplearning, there was a problem that the model did not work due to the problem of computer (cpu, ram and etc). </p> <p>the model: 8 layers model<br> data: numpy array (20000, 20, 20, 3) </p> <p>So I tried to apply the queue to the model but it failed. </p> <p>This is what I want to do.<br> <a ...
<p>In this case you can use <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/train/slice_input_producer" rel="nofollow noreferrer"><code>tf.train.slice_input_producer</code></a></p> <pre><code>data_sample, label_sample = slice_input_producer( [all_data, all_target], num_epochs=None, shuffle...
python|numpy|tensorflow|neural-network|deep-learning
0
358,844
45,743,666
How can we save a Tensorflow model made from a contrib.learn.Classifier?
<p>I would like to save a model made from contrib.learn.Classifier but I don't know how to get to refer to its internal nodes. This is the code that I use in a vanilla Tensorflow model (y=W*x+b), and it works great.</p> <pre><code>W = tf.Variable([], dtype=tf.float32) b = tf.Variable([], dtype=tf.float32) x = tf.place...
<p>You can use the <code>export_savedmodel</code> function of the estimator that exports inference graph as a SavedModel into given dir., <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/learn/LinearClassifier" rel="nofollow noreferrer"><code>tf.contrib.learn.LinearClassifier</code></a></p> <pre><code>fr...
tensorflow
0
358,845
46,147,019
Keras: difference of InputLayer and Input
<p>I made a model using Keras with Tensorflow. I use <code>Inputlayer</code> with these lines of code: </p> <pre><code>img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, a...
<ul> <li><code>InputLayer</code> is a layer. </li> <li><code>Input</code> is a tensor. </li> </ul> <p>You can only call layers passing tensors to them. </p> <p><strong>The idea is:</strong></p> <pre><code>outputTensor = SomeLayer(inputTensor) </code></pre> <p>So, only <code>Input</code> can be passed because it's...
tensorflow|keras
25
358,846
45,830,081
How does reuse option in tf.variable_scope work?
<pre><code>from __future__ import print_function import tensorflow as tf def _var_init(name, shape, initializer=tf.contrib.layers.xavier_initializer(), trainable=True): with tf.device('/cpu:0'): var = tf.get_variable( name=name, shape=shape, initializer=initializer, trainabl...
<p>From the official documentation of Tensorflow this is all that explains the reuse option:</p> <p>This is a basic example of sharing a variable:</p> <pre><code>with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v", [1]) assert v1 =...
python|tensorflow|with-statement
2
358,847
46,168,466
I want to know the size of bounding box in object-detection api
<p>I have used the <code>API</code> </p> <p><strong>(<a href="https://github.com/tensorflow/models/tree/master/object_detection" rel="noreferrer">https://github.com/tensorflow/models/tree/master/object_detection</a>)</strong></p> <p>And then,</p> <p>How would I know the length of bounding box?</p> <p>I have used Tu...
<p>Just to extend Beta's answer:</p> <p>You can get the predicted bounding boxes from the detection graph. An example for this is given in the <a href="https://github.com/tensorflow/models/blob/master/object_detection/object_detection_tutorial.ipynb" rel="noreferrer">Tutorial IPython notebook on github</a>. This is wh...
tensorflow|object-detection
12
358,848
45,949,258
Google Object Detection API: Fluctuation in TotalLoss
<p>I am using Google Object Detection API with my own dataset. Mostly after 50K steps it begins to converge with 60 percents accuracy. I think it works fine in general. But when if you look at TotalLoss graphic or in general all loss graphics, it fluctuates so much. It looks like this: </p> <p><a href="https://i.stack...
<p>Yes, fluctuation in the loss is very normal particularly because the detection pipelines are usually trained with small batch sizes (batch size 1 in the case of Faster R-CNN), so you typically only see a meaningful decrease in the loss if you average over many steps.</p>
image-processing|tensorflow|conv-neural-network|object-detection
3
358,849
45,955,241
How do I create padded batches in Tensorflow for tf.train.SequenceExample data using the DataSet API?
<p>For training an <strong>LSTM model</strong> in <strong>Tensorflow</strong>, I have structured my data into a <strong>tf.train.SequenceExample</strong> format and stored it into a <strong>TFRecord file</strong>. I would now like to use the new DataSet API to <strong>generate padded batches for training</strong>. In <...
<p>You need to pass a tuple of shapes. In your case you should pass </p> <pre><code>dataset = dataset.padded_batch(4, padded_shapes=([vectorSize],[None])) </code></pre> <p>or try </p> <pre><code>dataset = dataset.padded_batch(4, padded_shapes=([None],[None])) </code></pre> <p>Check this <a href="https://github.com/...
python|tensorflow|lstm|tensorflow-datasets
14
358,850
45,745,810
Play square wave SciPy and PyAudio
<p>I'm trying to play square waves generated using SciPy with PyAudio but I get the error</p> <blockquote> <p>TypeError: len() of unsized object</p> </blockquote> <p>which is kind of strange because the square wave object should have a size, right?</p> <pre><code>RATE = 48000 p = pyaudio.PyAudio() stream = p.open(...
<p>I get the same error. However, you are omitting some information, so I will assume these are your imports:</p> <pre><code>import pyaudio import math import numpy as np from scipy import signal </code></pre> <p>And that</p> <pre><code>FREQ = 440 </code></pre> <p>It looks like the variable you are iterating is <co...
python|numpy|scipy|pyaudio
0
358,851
46,083,368
Scipy: Two ways of implementing a differential equation: two different solutions: answered
<p>I was trying to solve a differential equation for my thesis in chemistry and there I stumbled over a question regarding the differential equation solver "odeint" of scipy.</p> <p>First I implemented the differential by the function CIDNP_1 (CIDNP is a chemical phenomena, that explains the unusual variables) accordi...
<p>In your first version you perform the updates not at the same time, as you execute the to lines</p> <pre><code>dP_dt = -kt*dP_dt*R(t) - kt*beta*(R(t))**2 dQ_dt = +kt*dP_dt*R(t) + kt*beta*(R(t))**2 </code></pre> <p>not simulatnously; therefore, you use the already updated <code>dP_dt</code> to update <code>dQ_dt</c...
python|numpy|scipy|differential-equations
1
358,852
45,995,799
Tensorflow train.batch issue
<p>I have a dataset with 40 feature values for each item. When I try to build a neural network using tensorflow( i am new to tensorflow), this line of the code, is raising an error.</p> <pre><code>for _ in range(n_batches): batches = tf.train.batch(input_list, batch_size=batch_size, enqueue_many=True, capa...
<p>You should convert the input list to a single array first. You can supply a list of tensors/arrays to <code>tf.batch</code> but then every tensor will be split in batches of size <code>40</code>. Currently you are supplying a list of tensors that have batch size <code>1</code> and you are asking to create batches of...
python|tensorflow|neural-network
1
358,853
46,114,964
LookUpError in TensorFlow with tf.cond()
<p><strong>Work environment</strong></p> <ul> <li>TensorFlow release version : 1.3.0-rc2</li> <li>TensorFlow git version : v1.3.0-rc1-994-gb93fd37</li> <li>Operating System : CentOS Linux release 7.2.1511 (Core)</li> </ul> <p><strong>Problem Description</strong></p> <p>I use <code>tf.cond()</code> to move between tr...
<p>The variable <code>worktype</code> is marked as trainable. By default, <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/train/Optimizer#compute_gradients" rel="nofollow noreferrer">Optimizer.compute_gradients(...)</a> computes the gradients for all trainable variables.</p> <p>There are two way...
tensorflow
1
358,854
46,100,962
Loop to get rolling future values of a pandas time-indexed dataframe, can I make this faster?
<pre><code>data['rolling_avg_val'] = 0 future_window = '1h' for i in range(data.shape[0]): start_data_idx = data.index[i] end_data_idx = start_data_idx + pd.Timedelta(future_window) temp_avg = data['values'][start_data_idx:end_data_idx].mean() if temp_avg == 0: continue ...
<p>reverse df</p> <p>flip index sign (from monotone decreasing to increasing</p> <p>rolling.mean()</p> <p>flip index sign again</p> <p>reverse df again</p> <pre><code>df2 = df[::-1] df2.index = pd.datetime(2050,1,1) - df2.index df2 = df2.rolling('1H').mean() df3 = df2[::-1] df3.index = df.index </code></pre>
python|pandas|numpy
7
358,855
45,805,685
Vectorization to calculate many distances
<p>I am new to numpy/pandas and vectorized computation. I am doing a data task where I have two datasets. Dataset 1 contains a list of places with their longitude and latitude and a variable A. Dataset 2 also contains a list of places with their longitude and latitude. For each place in dataset 1, I would like to calcu...
<p>If you can project the coordinates to a local projection (e.g. <a href="https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system" rel="nofollow noreferrer">UTM</a>), which is pretty straight forward with <code>pyproj</code> and generally more favorable than lon/lat for measurement, then there is...
python|pandas|numpy|vectorization
3
358,856
45,824,724
Is t-SNE's computational bottleneck its memory complexity?
<p>I've been exploring different dimensionality reduction algorithms, specifically PCA and T-SNE. I'm taking a small subset of the MNIST dataset (with ~780 dimensions) and attempting to reduce the raw down to three dimensions to visualize as a scatter plot. T-SNE can be described in great detail <a href="http://www.cs....
<p>t-SNE tries to lower the dimensionality while preserving the distributions of distances between elements.</p> <p>This requires computing distances between all the points. Pairwise distance matrix has N^2 entries where N is the number of examples.</p>
python|arrays|algorithm|numpy|dimensionality-reduction
2
358,857
45,869,287
Pandas Dataframe column value split
<p>I have an excel dataset containing usertype, ID and description of properties. I have imported this file in python pandas in dataframe(df).</p> <p>Now I want to split the contents in desciption into one word, two words and three words. I am able to do one word tokenization with the help of NLTK library. But I am st...
<p>Here is a small example using <code>ngrams</code> from the <code>nltk</code>. Hope it helps:</p> <pre><code>from nltk.util import ngrams from nltk import word_tokenize # Creating test dataframe df = pd.DataFrame({'text': ['my first sentence', 'this is the second sentence', ...
python-3.x|pandas|nltk
1
358,858
45,773,555
Why python array arr2d[:2,1:] produces following result?
<p>The following:</p> <pre><code>arr2d = np.array([[5,10,15],[15,20,25],[30,35,40]]) arr2d[:2,1:] </code></pre> <p>Produces:</p> <pre><code>array([[10, 15], [20, 25]]) </code></pre> <p>I would like to know how the result is calculated.</p>
<p>I think you want to read <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow noreferrer">about Numpy indexing</a></p> <pre><code>In [54]: arr2d[:2,1:] Out[54]: array([[10, 15], [20, 25]]) </code></pre> <p>means - give me first two rows and all columns starting from the se...
python|arrays|numpy
0
358,859
45,987,908
Storing arrays in Python for loop
<p>Let's say I have a function (called numpyarrayfunction) that outputs an array every time I run it. I would like to run the function multiple times and store the resulting arrays. Obviously, the current method that I am using to do this - </p> <pre><code>numpyarray = np.zeros((5)) for i in range(5): numpyarray[i...
<p>As comments and other answers have already laid out, a good way to do this is to store the arrays being returned by <code>numpyarrayfunction</code> in a normal Python list.</p> <p>If you want everything to be in a single numpy array (for, say, memory efficiency or computation speed), and the arrays returned by <cod...
python|python-3.x|numpy
5
358,860
45,788,593
Applying complex functions on pandas data frame
<p>I have a df of line segments, each line segment is identified by a unique id <strong>id</strong> and <strong>x</strong> and <strong>y</strong> coordinates.</p> <p>df:</p> <pre><code> id x y 0 1 0.1 0.2 1 1 0.6 1.2 2 1 2.2 1.6 3 1 2.3 1.9 4 2 0.4 0.9 5...
<p>I think @cᴏʟᴅsᴘᴇᴇᴅ can provide more efficient way , but you can try this . </p> <pre><code>LIST=[] for name,df2 in df.groupby("id"): new_x = np.linspace(df2["x"].max(), df2["x"].min(), 8) new_y = interpolate.interp1d(df2["x"], df2["y"], kind='cubic')(new_x) New_df = pd.DataFrame({'id':name,'new_x': new_...
python|pandas|numpy|dataframe|scipy
1
358,861
23,329,988
Retrieving groups by their index. Are Pandas groups sorted?
<p>Say I group a Pandas dataframe around some column</p> <pre><code>df.groupby(cols) </code></pre> <p>Are groups sorted according to any criteria?</p> <p>One way to retrieve a group is:</p> <pre><code>ix = 0 grouped.get_group(grouped.groups.keys()[ix]) </code></pre> <p>but it is a bit verbose, and it's not clear t...
<p><code>groupby</code> has a <code>sort</code> parameter which is <code>True</code> by default, thus the groups are sorted. As for getting the <code>n</code>th group, it looks like you'd have to define a function, and use an internal API:</p> <pre><code>In [123]: df = DataFrame({'a': [1,1,1,1,2,2,3,3,3,3], 'b': randn...
python|pandas
2
358,862
23,128,788
What is the Python numpy equivalent of the IDL # operator?
<p>I am looking for the Python <code>numpy</code> equivalent of the <a href="http://en.wikipedia.org/wiki/Interactive_Data_Language" rel="nofollow">IDL</a> # operator. Here is what the <a href="http://www.exelisvis.com/docs/manipulating_arrays.html#arrays_3727706888_752395" rel="nofollow"># operator</a> does:</p> <blo...
<p>Reading the notes on IDL's definition of matrix multiplication, it seems they use the opposite notation to everyone else:</p> <blockquote> <p>IDL’s convention is to consider the first dimension to be the column and the second dimension to be the row</p> </blockquote> <p>So # can be achieved by the rather stran...
python|arrays|numpy|matrix-multiplication|idl-programming-language
2
358,863
23,145,127
Scipy labels and measuring max pixel in each label
<p>So I want to measure the max pixel and average of pixels in each label(in multiple array) using scipy. for example</p> <p>(img , other is a numpy array of an opened tif)</p> <pre><code>import numpy as np import scipy.ndimage as ndi a = img &gt; 200 labels,nb = ndi.labels(a) merge = np.zeros(img.shape) merge = ot...
<p>You can use <code>labeled_comprehension</code> to do this all in one shot:</p> <pre><code>#!/usr/bin/env python2.7 import numpy as np from scipy import ndimage as nd hist = [] def analyze(x): xmin = x.min() xmax = x.max() xmean = x.mean() xhist = np.histogram(x, range=(xmin, xmax)) hist.appen...
python|numpy|scipy|ipython|ndimage
1
358,864
22,969,897
numpy: broadcast matrix multiply accross array
<p>I have a <code>3xN</code> array, conceptually an array of <code>N</code> 3-vectors, I want to construct the array which results from matrix multiplying a given <code>3x3</code> matrix with each column of the array. Is there a good way to do this in a vectorized manner?</p> <p>Currently, my problem is <code>3xN</...
<p>Using np.einsum function you can do it even for the multi dimension problem:</p> <pre><code>U = np.random.rand(3,24,5) R = np.eye(3,3) result = np.einsum( "ijk,il", U,R ) </code></pre> <p>The notation is a little tricky: the string you give first states the indeces of the dimensions of the arrays; so for U the in...
python|arrays|numpy|matrix
4
358,865
35,613,875
While Loop and Pandas Iterrows
<p>I am using Python 2.7 on Windows 10 and the Spyder Python IDE</p> <p>I am trying to calculate posterior conditional probabilities of reaching any node in a network from any other node. The network is defined by a <code>dataframe</code> where each row is a directional connection (called <code>edge</code> in graph th...
<pre><code>import pandas as pd df = pd.DataFrame({'fld1': ['apple', 'apple', 'bear','bear','car','car','car','dee','dee','eagle','eagle'] , 'fld2': ['bear', 'car', 'car','eagle','bear','dee','eagle','eagle','foo','dee','foo'] , 'value': [.3,.3,.2,.1,.3,.3,.2,.4,.1,.3,.2]}) gsums = df.groupby("fld1").su...
python|pandas|while-loop|dataframe
1
358,866
35,402,566
Merging 2 columns within 1 pandas dataframe
<p>Given 2 different dataframes, I would actually like to map column <code>D</code> in <code>df1</code> and column <code>E</code> in <code>df2</code> as <code>New</code> on my appended dataframe.</p> <p>Below are my test codes.</p> <pre><code>df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], ...: ...
<p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a> columns <code>D</code> and <code>E</code> before <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow"><code>append...
python|pandas|merge|dataframe
0
358,867
35,492,618
How to replace NaNs by average of preceding and succeeding values in pandas DataFrame?
<p>If I have some missing values and I would like to replace all NaN with average of preceding and succeeding values, how can I do that ?.</p> <p>I know I can use <code>pandas.DataFrame.fillna</code> with <code>method='ffill'</code> or <code>method='bfill'</code> options to replace the NaN values by preceding or succe...
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html#interpolation" rel="noreferrer"><code>DataFrame.interpolate()</code></a>. Example from the panda docs:</p> <pre><code>In [65]: df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], ....: 'B': [.25, np.nan, np.nan, 4...
python|python-3.x|pandas
5
358,868
35,492,556
How to update an SVM model with new data
<p>I have two data set with different size.</p> <p>1) Data set 1 is with high dimensions 4500 samples (sketches).</p> <p>2) Data set 2 is with low dimension 1000 samples (real data). I suppose that "both data set have the same distribution"</p> <p>I want to train an non linear <code>SVM</code> model using <code>skle...
<p>In sklearn you can do this only for linear kernel and using <code>SGDClassifier</code> (with appropiate selection of loss/penalty terms, loss should be hinge, and penalty L2). Incremental learning is supported through <code>partial_fit</code> methods, and this is not implemented for neither <code>SVC</code> nor <cod...
python|numpy|machine-learning|computer-vision|scikit-learn
12
358,869
35,690,067
Duplicating pandas dataframe vertically
<p>I have the foll. dataframe:</p> <pre><code> Month Day season 0 4 15 current 1 4 16 current 2 4 17 current 3 4 18 current 4 4 19 current 5 4 20 current </code></pre> <p>I would like to duplicate it like so:</p> <pre><code> Month Day season 0 4...
<p>I think this would be a good case for <code>assign</code> since it allows you to keep your functional programming style (i approve!)</p> <pre><code>In [144]: df.append([df.assign(season='past')]*2,ignore_index=True) Out[144]: Month Day season 0 4 15 current 1 4 16 current 2 4 17 c...
python|pandas
1
358,870
35,655,693
Python packages for Spark on datanodes
<p>We want to use Python 3.x with packages like NumPy, Pandas,etc. on top of Spark.</p> <p>We know the Python distribution with these packages needs to be present/distributed on all the datanodes for Spark to use these packages.</p> <p>Instead of setting up this Python distro on all the datanodes, will putting it on ...
<p>Yes, putting the packages on a NAS mount to which all the datanodes are connected will work up to dozens and perhaps 100 nodes if you have a good NAS. However, this solution will break down at scale as all the nodes try to import the files they need. The Python import mechanism usese a lot of os.stat calls to th...
python|numpy|apache-spark|pyspark
2
358,871
35,356,933
loading a sparse matrix saved with np.save
<p>I saved a scipy csr matrix using <code>np.save('X', X)</code>. When I load it with <code>np.load('X.npy')</code>, I get this signiture: </p> <p><code>array(&lt;240760x110493 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20618831 stored elements in Compressed Sparse Row format&gt;, dtype=object)</c...
<p>Let's pay attention to all the clues in the print</p> <pre><code>array(&lt;240760x110493 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20618831 stored elements in Compressed Sparse Row format&gt;, dtype=object) </code></pre> <p>Outermost:</p> <pre><code>array(....,dtype=object) </code></pre> <p...
python|numpy|matrix|scipy
4
358,872
35,430,479
Convert sympy expressions to function of numpy arrays
<p>I have a system of ODEs written in sympy:</p> <pre><code>from sympy.parsing.sympy_parser import parse_expr xs = symbols('x1 x2') ks = symbols('k1 k2') strs = ['-k1 * x1**2 + k2 * x2', 'k1 * x1**2 - k2 * x2'] syms = [parse_expr(item) for item in strs] </code></pre> <p>I would like to convert this into a vector val...
<p>You can use the sympy function <a href="http://docs.sympy.org/latest/modules/utilities/lambdify.html"><code>lambdify</code></a>. For example,</p> <pre><code>from sympy import symbols, lambdify from sympy.parsing.sympy_parser import parse_expr import numpy as np xs = symbols('x1 x2') ks = symbols('k1 k2') strs = [...
python|numpy|scipy|sympy
14
358,873
35,353,891
Pandas: Dict of data frames to unbalanced Panel
<p>I have a dictionary of DataFrame objects:</p> <p>dictDF={0:df0,1:df1,2:df2}</p> <p>Each DataFrame df0,df1,df2 represents a table in a specific date of time, where the first column identifies (like social security number) a person and the other columns are characteristics of this person such as</p> <pre><code>Data...
<p>I would recommend using a MultiIndex instead of a Panel.</p> <p>First, add the period to each dataframe:</p> <pre><code>for n, df in dictDF.iteritems(): df['period'] = n </code></pre> <p>Then concatenate into a big dataframe:</p> <pre><code>big_df = pd.concat([df for df in dictDF.itervalues()], ignore_index=...
python|dictionary|pandas|dataframe
1
358,874
35,585,915
Does Tensorflow have optimizers for compute graphs involving complex64 tensors?
<p>The tf.float32 version of the following code works. However, when we try to run the following, we get an exception (on the line where we try to define an optimizer).</p> <pre><code>import tensorflow as tf tf.InteractiveSession() complex_weights = tf.Variable(tf.complex(tf.truncated_normal([3, 4]), ...
<p>Yes, you hit intermediate op that didn't have complex support. See this <a href="https://stackoverflow.com/questions/35443080/tensorflow-critical-graph-operations-assigned-to-cpu-rather-than-gpu">question</a> for some pointers to code where you can see which data types are registered for which devices. In general I ...
tensorflow
2
358,875
35,668,472
How can i search a array from a large array by numpy
<p>I am beginning at numpy! Has numpy some function can search an array from another one ,and return the similar ones? Thanks!</p> <pre><code>import numpy as np def searchBinA(B = ['04','22'],A): result = [] ?......? numpy.search(B,A)? "is this correct?" return result A = [['03', '04', '18', '22', '...
<p>Assuming the inputs are NumPy arrays and that there are no duplicates within each row of <code>A</code>, here's an approach using <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> -</p> <pre><code>A[np.in1d(A,B).reshape(A.shape).sum(1) == le...
python|numpy
1
358,876
35,510,143
python & pandas: get average rank
<p>I have a data frame</p> <pre><code>ID 2014-01-01 2015-01-01 2016-01-01 1 NaN 0.1 0.2 2 0.1 0.3 0.5 3 0.2 NaN 0.7 4 0.8 0.4 0.1 </code></pre> <p>For each date(col), I want to get ...
<p>it's unclear why you think the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rank.html#pandas.DataFrame.rank" rel="nofollow"><code>rank</code></a> should be <code>4</code> for the first row value in the second column but the following gives you what you want. Here we call <code>rank...
python|pandas
2
358,877
35,382,336
dumping several objects into the same file
<p>Let's say I have a dictionary of about 100k pairs of strings, and a numpy matrix of shape (100k, 500). I would like to save them to the disk in a same file.</p> <p>What I'm doing right now is using cPickle to dump the dictionary, and scipy.io.savemat to dump the matrix. This way, the dump / load is very fast. But t...
<p>You could use <code>dill</code>. <code>dill.dump</code> accesses and uses the <code>dump</code> method from <code>numpy</code> to store an <code>array</code> or <code>matrix</code> object, so it's stored the same way it would be if you did it directly from the method on the <code>numpy</code> object. You'd just <c...
python|numpy|scipy|pickle
0
358,878
35,719,952
delete part of a row in pandas / shift up part of a row ? Align Column Headings
<p>So I have a data frame where the headings I want do not currently line up:</p> <pre><code> In [1]: df = pd.read_excel('example.xlsx') print (df.head(10)) Out [1]: Portfolio Asset Country Quantity Unique Identifier Number of fund B24 ...
<p>IIUC you can use:</p> <pre><code>#create df from multiindex in columns df1 = pd.DataFrame([x for x in df.columns.values]) print df1 0 1 0 Unique Identifier 1 Number of fund 2 Portfolio B24 3 Asset B65 4 Country ...
python|excel|pandas
2
358,879
35,567,497
Pandas and Yahoo ChartAPI
<p>I am trying to read from <a href="http://chartapi.finance.yahoo.com/instrument/1.0/EURUSD=X/chartdata;type=quote;range=1y/csv" rel="nofollow">this source - Yahoo Finance</a> from line 17 onwards. I want to get the date, highprice, lowprice, etc, which are the 6 columns.</p> <p>My code:</p> <pre><code>import pandas...
<p>According to the document, <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table" rel="nofollow"><code>pandas.read_csv</code></a> need a file-like object as the first parameter. </p> <p>So you can either save the file locally and re-read it using <code>pandas.read_csv</code> method, or you ...
api|python-3.x|pandas|urllib|yahoo-finance
1
358,880
35,660,823
How can I format a float to separate by thousands, inverting dot and commas?
<p>How can I format a float, from a pandas dataframe, to separate thousands by dots and commas, instead by commas and dots? ?</p> <p>Input:</p> <pre><code>112299420.40 </code></pre> <p>Actual output:</p> <pre><code>112,299,420.40 </code></pre> <p>Required output:</p> <pre><code>112.299.420,40 </code></pre> <p>My...
<p>Python 2.7 string formatting features don't seem to help in this case. However, you can use the <code>locale</code> module and set your locale to a country/language which uses the thousands/decimal separators you want (in the example below, Brazilian Portuguese):</p> <pre><code>import locale locale.setlocale(locale...
python|pandas|format|dataframe
3
358,881
35,743,624
Resize a batch of images in numpy
<p>I have close to 10000 greyscale images in a numpy array (10000 x 480 x 752) and would like to resize them with the imresize function from scipy.misc. It works with a for loop build around all the images, but it takes 15 minutes.</p> <pre><code>images_resized = np.zeros([0, newHeight, newWidth], dtype=np.uint8) for ...
<p>the time is long probably because <code>resize</code> is long :</p> <pre><code>In [22]: %timeit for i in range(10000) : pass 1000 loops, best of 3: 1.06 ms per loop </code></pre> <p>so the time is spend by the <code>resize</code> function: Vectorisation will not improve performance here.</p> <p>Estimate time for ...
python|numpy|image-resizing
4
358,882
35,345,318
Unknown characters in column name
<p>I have a df like this:</p> <pre><code>Allotments NDWI TWI 1 2 4 2 3 6 </code></pre> <p>and I am trying to rename the columns, but when I print:</p> <pre><code>df.columns.values </code></pre> <p>this is returned:</p> <pre><code>['\xef\xbb\xbfAllotments' 'NDWI' 'TWI'] </code></...
<p>You can pass <code>encoding='utf-8'</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow"><code>read_csv</code></a> as a kwarg so it decodes the BOM correctly.</p>
python|pandas
1
358,883
11,690,793
How to work with matplotlib?
<p>One of the graph generation files of Python is Matplotlib("<a href="http://matplotlib.org/" rel="nofollow">http://matplotlib.org/</a>"). I am using Python3.2.1 on Windows7(64bit) O/S. I am trying to download the same to run matplotlib.animation. </p> <p>If any one of the esteemed members of the group may kindly s...
<p>I dont believe full support of python 3 has been added to matplotlib. Here is <a href="https://github.com/matplotlib/matplotlib-py3/wiki/" rel="nofollow">the status page</a>. </p> <p><a href="http://matplotlib.sourceforge.net/users/whats_new.html" rel="nofollow">It will support it on the next release</a>.</p> <p>I...
python|numpy|python-3.x|matplotlib
2
358,884
11,777,251
Python/numpy append arrays, transpose, and save as csv
<p>What I am doing: generating a series of long 1D arrays. </p> <p>What I want to do: append/concatentate/vstack/? these into a 2D array, then save the rows as columns in a csv file.</p> <p>The following works, but it's not elegant:</p> <pre><code>rlist=[] # create empty list for i in range(...
<p>If you know the length of <code>r</code> and <code>nnn</code> in advance, you can do:</p> <pre><code>rarr = np.zeros((r_len, nnn)) # r_len rows, nnn columns for i in range(nnn): rarr[:,i] = r_calc() numpy.savetxt('test.csv', rarr, delimiter=',') </code></pre> <p>This puts the data vectors directly into rows of...
python|arrays|list|numpy|transpose
1
358,885
11,597,727
Scientific modules for Ruby
<p>I've been using quite a number of Python modules such as Numpy in large machine learning projects. Previously, I used Django for the web application and mod_wsgi as a front end to these. Now, someone is making the case to transfer to Ruby on Rails. Are similar libraries available for Ruby?</p>
<p>As Benjamin Tan pointed out, <a href="http://sciruby.com" rel="nofollow">SciRuby</a> is working on this. Commenters rightly noted that not much work has been done on the <a href="http://github.com/SciRuby/sciruby" rel="nofollow">sciruby gem</a>, but <a href="http://github.com/SciRuby/nmatrix" rel="nofollow">NMatrix<...
ruby|numpy|mod-wsgi
2
358,886
11,879,268
How to pass complex numbers from python numpy to c (trying to use SWIG at the moment)
<p>I want to call c written functions with complex numbered inputs and in python. I've tried using SWIG to generate a wrapper - but it seems to fall down. I think i need to work out the proper 'macro' for use in numpy.i - but not sure what it is - anyone have any experience in this - or other ways I can work around t...
<p>I'm not sure how this interacts with Numpy, but SWIG certainly includes support for C99's complex types. I was able to verify this with the following example:</p> <pre><code>%module test %{ #include &lt;complex.h&gt; %} %include &lt;complex.i&gt; %inline %{ double complex test(double complex X) { return X; ...
python|c|numpy|swig
3
358,887
11,963,148
Sharing numpy arrays in python multiprocessing pool
<p>I'm working on some code that does some fairly heavy numerical work on a large (tens to hundreds of thousands of numerical integrations) set of problems. Fortunately, these integrations are embarassingly parallel, so it's easy to use Pool.map() to split up the work across multiple cores.</p> <p>Right now, I have a...
<p>I had a similar problem. If you just want to read my solution skip some lines :) I had to:</p> <ul> <li>share a numpy.array between threads operating on different part of it and...</li> <li>pass Pool.map a function with more then one argument.</li> </ul> <p>I noticed that:</p> <ul> <li>the data of the numpy.array...
python|numpy|scipy|multiprocessing
5
358,888
11,994,765
pandas DataFrame.to_string() truncating strings from columns
<p>When I try to use to_string to output a column from a <code>dataframe</code>, it truncates the output of the column.</p> <pre><code>print gtf_df.ix[:1][['transcript_id','attributes']].to_string(header=False,index=False) Out: ' CUFF.1.1 gene_id "CUFF.1"; transcript_id "CUFF.1.1"; FPKM ' print gtf_df.ix[:1]['attri...
<p>Using <code>__repr__</code> or <code>to_string</code> columns are by default truncated at 50 chars. In versions of Pandas older than 0.13.1, this can be controlled using <code>pandas.set_printoptions()</code>:</p> <pre><code>In [64]: df Out[64]: A B a this is a...
python|pandas
12
358,889
28,646,336
Pretty printing polynomials in IPython notebook
<p>I have some polynomial <code>x</code> in IPython notebook: </p> <pre><code>import numpy as np x = np.polynomial.polynomial.Polynomial([1,2,3]) x </code></pre> <p>Then <code>x</code> is printed as <code>Polynomial([ 1., 2., 3.], [-1., 1.], [-1., 1.])</code> which is to be honest ugly. How can I have normal ...
<p>You can use sympy's Poly class to render your polynomials to nice latex. The only issue here, is that numpy lists the coefficients in order of increasing degree, whereas sympy does the opposite.</p> <pre><code>In [1]: import numpy as np ...: nppoly = np.polynomial.polynomial.Polynomial([1,2,3]) ...: nppoly Ou...
python|numpy|ipython|ipython-notebook
3
358,890
28,787,229
Pandas groupby rows with csv
<p>I have a large CSV file that I am pulling two columns from (Month and Cancelled) and needing to display the results in a dataframe. The months are integer (eg. January is 1 in the csv) and need to convert it to a string.</p> <p>What I'm having trouble with is setting the correct indices and grouping the data from t...
<p>Since you didn't post a row input data. Let's consider this quick example just to show how to make groupby values in pandas;</p> <p>After reading your data and puting in a dataframe, you can groupby values based on one of the columns <code>groupby(['month'])</code>, and then apply a function on these values,Pandas ...
python|csv|pandas|group-by|aggregate
0
358,891
28,752,126
Numpy fft.pack vs FFTW vs Implement DFT on your own
<p>I am currently need to run FFT on 1024 sample points signal. So far I have implementing my own DFT algorithm in python, but it is very slow. If I use the NUMPY fftpack, or even move to C++ and use FFTW, do you guys think it would be better?</p>
<p>If you are implementing the DFFT entirely within Python, your code will run <em>orders of magnitude</em> slower than either package you mentioned. Not just because those libraries are written in much lower-level languages, but also (FFTW in particular) they are written so heavily optimized, taking advantage of cache...
python|numpy|fft|fftw
7
358,892
28,820,157
Multiplying Columns Efficiently in pandas
<p>I want to multiply a set of columns <code>s_cols</code> with two other columns <code>b</code>, <code>c</code>.</p> <p>So far, I was doing</p> <pre><code>s_cols = ['t070101', 't070102', 't070103', 't070104', 't070105', 't070199', 't070201', 't070299'] dfNew = df[s_cols]*df[`c`]*df[`b`] </code></pre> <p>but that op...
<p>My guess is you actually want to do something like the following:</p> <pre><code>In [11]: cols = ['a', 'b'] In [12]: df1 Out[12]: a b c d 0 1 4 1 4 1 2 5 2 10 2 3 6 3 18 In [13]: df1[cols].multiply(df1['c'] * df1['d'], axis=0) Out[13]: a b 0 4 16 1 40 100 2 162 324 </code></p...
python|pandas
1
358,893
51,065,490
How to show original feature names in the feature importance plot?
<p>I created XGBoost model as follows:</p> <pre><code>y = XY.DELAY_MIN X = standardized_df train_X, test_X, train_y, test_y = train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25) my_imputer = preprocessing.Imputer() train_X = my_imputer.fit_transform(train_X) test_X = my_imputer.transform(test_X) xgb_mode...
<p>The issue is the <code>Imputer</code> doesn't return a <code>pd.DataFrame</code> as an output of <code>transform()</code>, thus, your column names get lost, when you do </p> <pre><code>train_X = my_imputer.fit_transform(train_X) test_X = my_imputer.transform(test_X) </code></pre> <p>Simple solution, wrap the imput...
python|pandas|xgboost
3
358,894
50,893,890
Tensorflow: Replacing Placeholders With Real Tensors In A Restored Metagraph
<p>(I'm on TF 1.7 right now, in case that matters.)</p> <p>I'm trying to initialize and then save a model and associated metagraph in one script (<code>init.py</code>) so that I can load the model and resume training from a second script (<code>train.py</code>). The model is initialized with placeholders for training ...
<p>I believe I've found the issue. The issue is that my Saver in <code>train.py</code> is saving the real input tensors that I've mapped in. When I try to restore, those real input tensors are restored from the disk, but not initialized.</p> <p>So: after running <code>input.py</code> one time, the following <code>trai...
tensorflow|tensorflow-datasets
0
358,895
51,049,326
pandas Dataframe Replace NaN values with with previous value based on a key column
<p>I have a pd.dataframe that looks like this:</p> <pre><code>key_value a b c d e value_01 1 10 x NaN NaN value_01 NaN 12 NaN NaN NaN value_01 NaN 7 NaN NaN NaN value_02 7 4 y NaN NaN value_02 NaN 5 NaN NaN NaN value_02 NaN 6 NaN NaN NaN value...
<h2><code>pd.concat</code> with <code>groupby</code> and <code>assign</code></h2> <pre><code>pd.concat([ g.ffill().assign(d=lambda d: d.b.shift(), e=lambda d: d.d.cumsum()) for _, g in df.groupby('key_value') ]) key_value a b c d e 0 value_01 1.0 1 x NaN NaN 1 value_01 1.0 2 x 1.0 ...
python|pandas|dataframe|pandas-groupby
3
358,896
50,963,289
replace numpy array loop in array calculations
<p>Hi is there a faster and easy option to do below code without using loop? When increasing multiplier value the computation is time expensive.</p> <pre><code>import numpy as np import random import timeit multiplier = 2 vectors_number = 4 * multiplier variable_number = 6 input_matrix = np.random.uniform(-5, 5, (vec...
<p>How about</p> <pre><code>out_matrix = input_matrix[winning_matrix[...,2]] - input_matrix[winning_matrix[...,1]] </code></pre> <p>Using </p> <pre><code>multiplier = 200 vectors_number = 4 * multiplier variable_number = 6000 </code></pre> <p>I get </p> <blockquote> <p>Computation time 1.576242</p> </blockquote>...
arrays|loops|numpy
0
358,897
50,747,136
Pandas df read every row, return SQL query with a new column in df
<p>I have the following pandas dataframe as df and I want to query each row of <code>df['item']</code> that will return corresponding <code>item_description</code> from a SQL Server database and populate df with columns 'id', 'qty', 'item', 'item_description'</p> <pre><code>| id | qty | item | +-----+------+------+ ...
<p>Change the SQL query to return both the item and item_description columns to give you a dataframe something like this:</p> <pre><code> item item_description 0 CB04 apple 1 AB01 orange </code></pre> <p>Then you have a common column that can be used to join the two dataframes with the <code>...
python|sql|pandas|dataframe
0
358,898
50,809,513
how to pool different shaped convolutional layer outputs to a fixed shape to pass for Fully connected layer
<p>I have different sized input images, and I am passing them through the Conv layers in a CNN after which I should connect the Conv outputs to a Fully Connected Layer for classification.</p> <p>Since the process has to be vectorised the outputs have to be of same shape so that a batch of images could be used for forw...
<p>If your inputs are consistent across examples (i.e. if <code>inputs = image1, image2</code>, then all your <code>image1</code>s are the same size, all your <code>image2</code>s are the same size, but <code>image1.shape</code> isn't necessarily the same as <code>image2</code> you could just flatten your final conv ou...
python|tensorflow|machine-learning|computer-vision|convolutional-neural-network
0
358,899
50,759,970
Get every nth element of multiple dataframes in pandas
<p>I have 10 dataframes with an identitcal structure all containing 10000 records. I want to create a matrix containing every 1000th record of all the different dataframes.</p> <p>So my dataset is as follows:</p> <pre><code>df = pd.read_csv('10000_0.csv') df1 = pd.read_csv('10000_1.csv') df2 = pd.read_csv('10000_2.cs...
<p>Use:</p> <pre><code>files = ['10000_{}.csv'.format(x) for x in range(10)] #list of all DataFrames dfs = [pd.read_csv(f) for f in files] #list of one row DataFrame L = [x.iloc[[1000]] for x in dfs] #list of Series L = [x.iloc[1000] for x in dfs] #final DataFrame df1 = pd.concat(L, ignore_index=True) </code></pre...
python|pandas
1