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
0
71,036,673
Why doesn't the for loop save each roll value in each iteration to the histogram?
<p>I am creating a for loop to inspect regression to the mean with dice rolls. Wanted outcome would that histogram shows all the roll values that came on each iteration.</p> <p>Why doesn't the for loop save each roll value in each iteration to the histogram?</p> <p>Furthermore PyCharm takes forever to load if n&gt; 200...
<p>You are now overwriting h and h2 in every iteration. Instead, you could append the values to a list and make a histogram of the entire list:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt sums = 0 values = [1, 2, 3, 4, 5, 6] numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]...
python|numpy|matplotlib
1
1
51,636,753
How to sort strings with numbers in Pandas?
<p>I have a Python Pandas Dataframe, in which a column named <code>status</code> contains three kinds of possible values: <code>ok</code>, <code>must read x more books</code>, <code>does not read any books yet</code>, where <code>x</code> is an integer higher than <code>0</code>.</p> <p>I want to sort <code>status</co...
<p>Use:</p> <pre><code>a = df['status'].str.extract('(\d+)', expand=False).astype(float) d = {'ok': a.max() + 1, 'does not read any book yet':-1} df1 = df.iloc[(-df['status'].map(d).fillna(a)).argsort()] print (df1) name status 0 Paul ok 2 Robert must read ...
python|python-3.x|pandas|sorting
10
2
51,569,238
Bar Plot with recent dates left where date is datetime index
<p>I tried to sort the dataframe by datetime index and then plot the graph but no change still it was showing where latest dates like 2017, 2018 were in right and 2008, 2009 were left.</p> <p><a href="https://i.stack.imgur.com/BP8yy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BP8yy.png" alt="ent...
<p>I guess you've not change your index to year. This is why it is not working.you can do so by:</p> <pre><code>df.index = pd.to_datetime(df.Date).dt.year #then sort index in descending order df.sort_index(ascending = False , inplace = True) df.plot.bar() </code></pre>
python|pandas|matplotlib|bar-chart|datetimeindex
0
3
51,647,773
Using matplotlib to obtain an overlaid histogram
<p>I am new to python and I'm trying to plot an overlaid histogram for a manipulated data set from <code>Kaggle</code>. I tried doing it with <code>matplotlib</code>. This is a dataset that shows the history of gun violence in USA in recent years. I have selected only few columns for <code>EDA</code>. </p> <pre><code>...
<p>Welcome to Stack Overflow! From next time, please post your data like in below format (not a link or an image) to make us easier to work on the problem. Also, if you ask about a graph output, showing the contents of desired graph (even with hand drawing) would be very helpful :)</p> <hr> <p><code>df</code></p> <p...
python|pandas|matplotlib|kaggle
0
4
51,878,397
Local scripts conflict with builtin modules when loading numpy
<p>There are many posts about relative/absolute imports issues, and most of them are about Python 2 and/or importing submodules. <strong>This is not my case</strong>: </p> <ul> <li>I am using Python 3, so absolute import is the default;</li> <li>(I have also reproduced this issue with Python 2);</li> <li>I am not tryi...
<p>"Absolute import" does not mean "standard library import". It means that <code>import math</code> always tries to import the <code>math</code> module, rather than the old behavior of trying <code>currentpackage.math</code> first if the import occurs inside a package. It does <em>not</em> mean that Python will skip n...
python|numpy|anaconda|conda
0
5
36,076,303
How do I apply this function to each group in my DataFrame
<p>Relatively new to Pandas, coming from an R background. I have a DataFrame like so</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'ProductID':[0,5,9,3,2,8], 'StoreID':[0,0,0,1,1,2]}) ProductID StoreID 0 0 0 1 5 0 2 9 0 3 3 ...
<p>Figured it out thanks to <a href="https://stackoverflow.com/a/26721325/2146894">this</a> answer.</p> <pre><code>df.groupby('StoreID').ProductID.apply(lambda x: x.rank()/len(x)) </code></pre>
python|pandas|dataframe
2
6
35,924,126
Appending columns during groupby-apply operations
<h3>Context</h3> <p>I have several groups of data (defined by 3 columns w/i the dataframe) and would like perform a linear fit and each group and then append the estimate values (with lower + upper bounds of the fit).</p> <h3>Problem</h3> <p>After performing the operation, I get an error related to the shapes of the...
<p>Yay, a non-hacky workaround exists</p> <pre><code>In [18]: gr = data.groupby(['location', 'era', 'chemical'], group_keys=False) In [19]: gr.apply(fake_model, formula='') Out[19]: location days era chemical conc ci_lower ci_upper fit 0 MW-A 2415 modern Chem1 5.40 -0.105610 -0.056310 1.3...
python|pandas
4
7
37,173,706
Handling value rollover in data frame
<p>I'm processing a dataframe that contains a column that consists of an error count. The problem I'm having is the counter rolls over after 64k. Additionally, on long runs the rollover occurs multiple times. I need a method to correct these overflows and get an accurate count.</p>
<p>I'm not sure that it always work correctly, but let's try:</p> <pre><code># groups g = df.groupby((df['count'].diff() &lt; 0).cumsum()) # mapping cumulative summand mp = df.groupby((df['count'].diff() &lt; 0).cumsum(), as_index=False).max().shift(1).fillna(0)['count'] # math for grp, chunk in g: df['count'] +...
python|pandas
1
8
41,818,379
Why do I have to import this from numpy if I am just referencing it from the numpy module
<p>Aloha!</p> <p>I have two blocks of code, one that will work and one that will not. The only difference is a commented line of code for a numpy module I don't use. Why am I required to import that model when I never reference "npm"?</p> <p>This command works:</p> <pre><code>import numpy as np import numpy.matlib...
<h2>Short Answer</h2> <p>This is because <code>numpy.matlib</code> is an optional sub-package of <code>numpy</code> that must be imported separately. </p> <p>The reason for this feature may be:</p> <ul> <li>In particular for <code>numpy</code>, the <code>numpy.matlib</code> sub-module redefines <code>numpy</code>'s ...
python|numpy
22
9
7,776,679
append two data frame with pandas
<p>When I try to merge two dataframes by rows doing:</p> <pre><code>bigdata = data1.append(data2) </code></pre> <p>I get the following error:</p> <blockquote> <pre><code>Exception: Index cannot contain duplicate values! </code></pre> </blockquote> <p>The index of the first data frame starts from 0 to 38 and the sec...
<p>The <code>append</code> function has an optional argument <code>ignore_index</code> which you should use here to join the records together, since the index isn't meaningful for your application.</p>
python|pandas
44
10
37,634,786
Using first row in Pandas groupby dataframe to calculate cumulative difference
<p>I have the following grouped dataframe based on daily data</p> <pre><code>Studentid Year Month BookLevel JSmith 2015 12 1.4 2016 1 1.6 2 1.8 3 1.2 4 2.0 MBrown 2016 1 3.0 2 3.2 ...
<p>OK, this should work, if we <code>groupby</code> on the first level and subtract BookLevel from the series returned by calling <code>transform</code> with <code>first</code> then we can add this as the new desired column:</p> <pre><code>In [47]: df['ProgressSinceStart'] = df['BookLevel'] - df.groupby(level='Student...
python|pandas
8
11
37,971,322
Column Order in Pandas Dataframe from dict of dict
<p>I am creating a pandas dataframe from a dictionary of dict in the following way :</p> <pre><code>df = pd.DataFrame.from_dict(stats).transpose() </code></pre> <p>I want the columns in a particular order but cant seem to figure out how to do so. I have tried this:</p> <pre><code>df = pd.DataFrame(columns=['c1','c2'...
<p>You could do:</p> <pre><code>df = pd.DataFrame.from_dict(stats).transpose().loc[:, ['c1','c2','c3']] </code></pre> <p>or just </p> <pre><code>df = pd.DataFrame.from_dict(stats).transpose()[['c1','c2','c3']] </code></pre>
python|dictionary|pandas|dataframe
2
12
31,521,475
Vectorization on nested loop
<p>I need to vectorize the following program : </p> <pre><code>y = np.empty((100, 100, 3)) x = np.empty((300,)) for i in xrange(y.shape[0]): for j in xrange(y.shape[1]): y[i, j, 0] = x[y[i, j, 0]] </code></pre> <p>Of course, in my example, we suppose that y[:, :, :]&lt;=299 Vectorization, as far as I k...
<p><code>np.apply_along_axis</code> could work, but it's overkill.</p> <p>First, there's a problem in your nested loop approach. <code>np.empty</code>, used to define <code>y</code>, returns an array of <code>np.float</code> values, which cannot be used to index an array. To take care of this, you have to cast the arr...
python|numpy|vectorization|nested-loops
2
13
31,296,285
Converting pandas dataframe to numeric; seaborn can't plot
<p>I'm trying to create some charts using weather data, pandas, and seaborn. I'm having trouble using lmplot (or any other seaborn plot function for that matter), though. I'm being told it can't concatenate str and float objects, but I used convert_objects(convert_numeric=True) beforehand, so I'm not sure what the issu...
<p>You need to assign the result to itself:</p> <pre><code>new = new.convert_objects(convert_numeric=True) </code></pre> <p>See the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html#pandas.DataFrame.convert_objects" rel="nofollow noreferrer">docs</a></p> <p><code>co...
python|numpy|pandas|plot|seaborn
2
14
64,531,149
Repeating Data and Incorrect Names in Pandas DataFrame count Function Results
<p>I have a question about the Pandas DataFrame <code>count</code> function.</p> <p>I'm working on the following code:</p> <pre><code>d = {'c1': [1, 1, 1, 1, 1], 'c2': [1, 1, 1, 1, 1], 'c3': [1, 1, 1, 1, 1], 'Animal': [&quot;Cat&quot;, &quot;Cat&quot;, &quot;Dog&quot;, &quot;Cat&quot;, &quot;Dog&quot;]} import pandas a...
<p>The count function counts (for each column as you've noted) the number of non-na / non-empty cells. In general, this could differ for each column if they have different missing values. After a groupby though, I don't think this would ever be the case.</p> <p>Like you mentioned though, I believe .size() is the functi...
python|pandas|dataframe|count
0
15
64,286,384
How to count number of unique values in pandas while each cell includes list
<p>I have a data frame like this:</p> <p>import pandas as pd import numpy as np</p> <pre><code>Out[10]: samples subject trial_num 0 [0 2 2 1 1 1 [3 3 0 1 2 2 [1 1 1 1 3 3 [0 1 2 2 1 4 [4 5 6 2 2 5 [0 8 8 2...
<p>You can use <code>collections.Counter</code> for the task:</p> <pre><code>from collections import Counter df['frequency'] = df['samples'].apply(lambda x: sum(v==1 for v in Counter(x).values())) print(df) </code></pre> <p>Prints:</p> <pre><code> samples subject trial_num frequency 0 [0, 2, 2] 1 ...
python|pandas|dataframe
2
16
47,705,684
TensorFlow: `tf.data.Dataset.from_generator()` does not work with strings on Python 3.x
<p>I need to iterate through large number of image files and feed the data to tensorflow. I created a <code>Dataset</code> back by a generator function that produces the file path names as strings and then transform the string path to image data using <code>map</code>. But it failed as generating string values won't wo...
<p>This is a bug affecting Python 3.x that was <a href="https://github.com/tensorflow/tensorflow/commit/17ba3a69f4c3509711a3da5eff3cb6be99e0936d#diff-6933e3bb88491e1a9d006c709aba017c" rel="nofollow noreferrer">fixed</a> after the TensorFlow 1.4 release. All releases of TensorFlow from 1.5 onwards contain the fix.</p> ...
tensorflow|tensorflow-datasets
6
17
47,860,314
Error while importing a file while working with jupyter notebook
<p>Recently I've been working with <code>jupyter</code> notebooks and was trying to read an excel file with pandas and it gives me the following error:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory</p> </blockquote> <p>But it works fine and reads the file with the exact same lines of co...
<p>Seems like an installation error, Do this,</p> <h1>For Python 2</h1> <pre><code>pip install --upgrade --force-reinstall --no-cache-dir jupyter </code></pre> <h1>For Python 3</h1> <pre><code>pip3 install --upgrade --force-reinstall --no-cache-dir jupyter </code></pre>
python|pandas|path|jupyter-notebook
1
18
47,760,015
Python Dataframe: How to get alphabetically ordered list of column names
<p>I currently am able to get a list of all the column names in my dataframe using: </p> <pre><code>df_EVENT5.columns.get_values() </code></pre> <p>But I want the list to be in alphabetical order ... how do I do that? </p>
<p>In order to get the list of column names in alphabetical order, try:</p> <pre><code>df_EVENT5.columns.sort_values().values </code></pre>
python|pandas|sorting|dataframe|field
2
19
47,587,633
How to reduce the processing time of reading a file using numpy
<p>I want to read a file and comparing some values, finding indexes of the repeated ones and deleting the repeated ones. I am doing this process in while loop. This is taking more processing time of about 76 sec. Here is my code:</p> <pre><code>Source = np.empty(shape=[0,7]) Source = CalData (# CalData is the log fil...
<p>In any case, this should imporve your timings, I think:</p> <pre><code>def lex_pick(Source): idx = np.lexsort((Source[:, 6], Source[:, 5], Source[:, 4])) # indices to sort by columns 4, then 5, then 6 # if dtype = float mask = np.r_[np.logical_not(np.isclose(Source[idx[:-1], 5], S...
python|file|numpy
0
20
47,767,546
Select subset of numpy.ndarray based on other array's values
<p> I have two numpy.ndarrays and I would like to select a subset of Array #2 based on the values in Array #1 (Criteria: Values > 1):</p> <pre class="lang-py prettyprint-override"><code>#Array 1 - print(type(result_data): &lt;class 'numpy.ndarray'&gt; #print(result_data): [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
<p>It turned out to be pretty straight forward:</p> <pre><code>selArray = test_data[result_data_&gt;1] </code></pre> <p>See also possible solution in comment from Nain!</p>
python|arrays|numpy
1
21
49,223,529
Transforming extremely skewed data for regression analysis
<p>I have a Pandas Series from a housing data-set (size of the series = 48,2491), named "exempt_land". The first 10 entries of this series are: </p> <pre><code>0 0.0 2 17227.0 3 0.0 7 0.0 10 0.0 14 7334.0 15 0.0 16 0.0 18 0.0 19 8238.0 Name: exempt_land, ...
<p>With all the zeros, you need to use a non-normal distribution. Some variety of Tobit might make sense here. (You can't transform discrete data and get less discrete data.)</p>
python|pandas|normal-distribution
0
22
48,980,261
pandas fillna is not working on subset of the dataset
<p>I want to impute the missing values for <code>df['box_office_revenue']</code> with the median specified by <code>df['release_date'] == x</code> and <code>df['genre'] == y</code> . </p> <p>Here is my median finder function below.</p> <pre><code>def find_median(df, year, genre, col_year, col_rev): median = df[(df...
<p>You mentioned</p> <blockquote> <p>I did the code below since I was getting some CopyValue error...</p> </blockquote> <p>The warning is important. You did not give your data, so I cannot actually check, but the problem is likely due to:</p> <pre><code>df[(df['release_year'] == i) &amp; (df[genre] &gt; 0)]['box_offic...
python|pandas|missing-data
3
23
58,836,772
Is there support for functional layers api support in tensorflow 2.0?
<p>I'm working on converting our model from tensorflow 1.8.0 to 2.0 but using sequential api's is quite difficult for our current model.So if there any support for functional api's in 2.0 as it is not easy to use sequential api's.</p>
<p>Tensorflow 2.0 is more or less made around the keras apis. You can use the tf.keras.Model for creating both sequential as well as functional apis.</p>
python-3.x|tensorflow|tensorflow2.0
1
24
58,763,438
Conditional ffill based on another column
<p>I'm trying to conditionally ffill a value until a second column encounters a value and then reset the first column value. Effectively the first column is an 'on' switch until the 'off' switch (second column) encounters a value. I've yet to have a working example using ffill and where.</p> <p>Example input:</p> <pr...
<p>Try:</p> <pre><code>df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int) </code></pre> <p>[out]</p> <pre><code> Start End 0 0 0 1 0 0 2 1 0 3 1 0 4 1 0 5 1 0 6 1 1 7 0 0 8 1 0 9 ...
python|pandas
2
25
58,705,193
Why does calling np.array() on this list comprehension produce a 3d array instead of 2d?
<p>I have a script produces the first several iterations of a Markov matrix multiplying a given set of input values. With the matrix stored as <code>A</code> and the start values in the column <code>u0</code>, I use this list comprehension to store the output in an array:</p> <pre><code>out = np.array([ ( (A**n) * u0)...
<p>I think your confusion lies with how arrays can be joined. </p> <p>Start with a simple 1d array (in <code>numpy</code> 1d is a real thing, not just a 'row vector' or 'column vector'):</p> <pre><code>In [288]: arr = np.arange(6) In [289]: arr ...
python|numpy
1
26
58,650,432
pandas df.at utterly slow in some lines
<p>I've got a .txt logfile with IMU sensor measurements which need to be parsed to a .CSV file. Accelerometer, gyroscope have 500Hz ODR (output data rate) magnetomer 100Hz, gps 1Hz and baro 1Hz. Wi-fi, BLE, pressure, light etc. is also logged but most is not needed. The smartphone App doesn't save all measurements sequ...
<p>This doesn't address the part of your question about sorting timestamps etc, but should be an efficient replacement for your <code>'ACCE'</code> parsing code. </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import collections as colls logs_file_path = '../resources/imu_logs_raw.txt' msmt_...
python|python-3.x|pandas|numpy|jupyter-notebook
0
27
70,330,361
Count values from different columns of a dataframe
<p>Let's say I have the following dataframe.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = { 'home': ['team1', 'team2', 'team3', 'team2'], 'away': ['team2', 'team3', 'team1', 'team1'] } df = pd.DataFrame(data) </code></pre> <p>How can I count the number of time each element (team)...
<p>You can concatenate the columns and use <code>.value_counts</code> method:</p> <pre><code>out = pd.concat([df['home'], df['away']]).value_counts() </code></pre> <p>Output:</p> <pre><code>team1 3 team2 3 team3 2 dtype: int64 </code></pre> <p>You can also get the underlying numpy array, <code>flatten</code> i...
python|pandas
3
28
70,334,785
Rename items from a column in pandas
<p>I'm working in a dataset which I faced the following situation:</p> <pre><code>df2['Shape'].value_counts(normalize=True) </code></pre> <pre><code>Round 0.574907 Princess 0.093665 Oval 0.082609 Emerald 0.068820 Radiant 0.059752 Pear 0.041739 Marquise 0.029938 Asscher 0.024099 Cus...
<p>Since you didn't state any restrictions, a quick fix will be that you can first change the entries the way you desire as shown below-</p> <pre><code>df2['Shape'][df2['Shape'] == 'Marquis'] = 'Marquise' df2['Shape'][df2['Shape'] == 'Marwise'] = 'Marquise' </code></pre> <p>Now, run this command,</p> <pre><code>df2['Sh...
python|pandas|dataframe
2
29
70,154,686
Replacing href dynamic tag in python (html body)
<p>I have a script that generates some body email from a dataframe to then send them to every user. The problem is that my content is dynamic and so the links I am sending to every user (different links for different users)</p> <p>The html body of the email is like:</p> <pre><code>&lt;table border=&quot;2&quot; class=&...
<p>I would do this in different way.</p> <p>First I would create column with <code>&lt;a href=&quot;{url}&quot;&gt;SOME TEXT&lt;/a&gt;</code></p> <pre class="lang-py prettyprint-override"><code>def convert(row): return f'&lt;a href={row[&quot;LINKS&quot;]}&gt;CLICK THIS LINK&lt;/a&gt;' df['LINKS_HTML'] = df.apply(...
python|html|pandas
0
30
70,236,604
xgboost model prediction error : Input numpy.ndarray must be 2 dimensional
<p>I have a model that's trained locally and deployed to an engine, so that I can make inferences / invoke endpoint. When I try to make predictions, I get the following exception.</p> <pre><code>raise ValueError('Input numpy.ndarray must be 2 dimensional') ValueError: Input numpy.ndarray must be 2 dimensional </co...
<p>I think the solution is to provide the test data as the same data type as the train data.</p> <p>Thank you for the comment. With the added information that after encoding the datatype of <code>X_train</code> is <code>scipy.sparse.csr.csr_matrix</code> and <code>y_train</code> is a <code>Pandas series</code>. If ther...
python|amazon-web-services|numpy|amazon-sagemaker
1
31
56,357,418
Get the average mean of entries per month with datetime in Pandas
<p>I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question). My df is something lik...
<p>You could do something like this:</p> <pre><code># count the total months in the records def total_month(x): return x.max().year -x.min().year + 1 new_df = ufo.groupby(ufo.Time.dt.month).Time.agg(['size', total_month]) new_df['mean_count'] = new_df['size'] /new_df['total_month'] </code></pre> <p>Output:</p> ...
python|pandas
2
32
56,397,461
How do I select the minimum and maximum values for a horizontal lollipop plot/dumbbell chart?
<p>I have created a dumbbell chart but I am getting too many minimum and maximum values for each category type. I want to display only one skyblue dot (the minimum price) and one green dot (the maximum price) per area. </p> <p>This is what the chart looks like so far:</p> <p><a href="https://i.stack.imgur.com/ZAXsV.p...
<p>As per conversation, here is the script:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('dumbbell data.csv') db = df[['minPrice','maxPrice', 'neighbourhood_hosts']] #create max and min price based on area name max_price = db.groupby(['nei...
python|pandas|numpy|matplotlib|seaborn
1
33
55,642,036
Finding the indexes of the N maximum values across an axis in Pandas
<p>I know that there is a method .argmax() that returns the indexes of the maximum values across an axis.</p> <p>But what if we want to get the indexes of the 10 highest values across an axis? </p> <p>How could this be accomplished?</p> <p>E.g.:</p> <pre><code>data = pd.DataFrame(np.random.random_sample((50, 40))) ...
<p>IIUC, say, if you want to get the index of the top 10 largest numbers of column <code>col</code>:</p> <pre><code>data[col].nlargest(10).index </code></pre>
python|pandas|argmax
0
34
55,768,432
How to create multiple line graph using seaborn and find rate?
<p>I need help to create a multiple line graph using below DataFrame</p> <pre><code> num user_id first_result second_result result date point1 point2 point3 point4 0 0 1480R clear clear pass 9/19/2016 clear consider clear consider 1 1 419M conside...
<p>Here's my idea how to do it:</p> <pre><code># first convert all `clear`, `consider` to 1,0 tmp_df = df[['first_result', 'second_result']].apply(lambda x: x.eq('clear').astype(int)) # convert `pass`, `fail` to 1,0 tmp_df['result'] = df.result.eq('pass').astype(int) # copy the date tmp_df['date'] = df['date'] # gr...
pandas|matplotlib|seaborn|linegraph
0
35
64,971,775
How to compare columns with equal values?
<p>I have a dataframe which looks as follows:</p> <pre><code> colA colB 0 2 1 1 4 2 2 3 7 3 8 5 4 7 2 </code></pre> <p>I have two datasets one with customer code and other information and the other with addresses plus related customer code.</p> <p>I did a merge with the two bases and n...
<p>you can try :</p> <pre><code>dfs=df.loc[df['colA']==df['colB']] </code></pre>
pandas
0
36
39,576,340
rename the pandas Series
<p>I have some wire thing when renaming the pandas Series by the datetime.date</p> <pre><code>import pandas as pd a = pd.Series([1, 2, 3, 4], name='t') </code></pre> <p>I got <code>a</code> is:</p> <pre><code>0 1 1 2 2 3 3 4 Name: t, dtype: int64 </code></pre> <p>Then, I have:</p> <pre><code>ts = pd.Se...
<p>Because <code>rename</code> does not change the object unless you set the <code>inplace</code> argument as <code>True</code>, as seen in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rename.html" rel="nofollow">docs</a>.</p> <p>Notice that the <code>copy</code> argument can be use...
python|python-2.7|pandas
2
37
39,598,618
Pandas Filter on date for quarterly ends
<p>In the index column I have a list of dates:</p> <pre><code>DatetimeIndex(['2010-12-31', '2011-01-02', '2011-01-03', '2011-01-29', '2011-02-26', '2011-02-28', '2011-03-26', '2011-03-31', '2011-04-01', '2011-04-03', ... '2016-02-27', '2016-02-29', '2016-03-26', '2016-03-31'...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.is_quarter_end.html#pandas.Series.dt.is_quarter_end" rel="noreferrer"><code>is_quarter_end</code></a> to filter the row labels:</p> <pre><code>In [151]: df = pd.DataFrame(np.random.randn(400,1), index= pd.date_range(start=dt...
python|datetime|pandas
5
38
39,715,686
Cannot get pandas to open CSV [Python, Jupyter, Pandas]
<p><strong>OBJECTIVE</strong></p> <p>Using Jupyter notebooks, import a csv file for data manipulation</p> <p><strong>APPROACH</strong></p> <ol> <li>Import necessary libraries for statistical analysis (pandas, matplotlib, sklearn, etc.)</li> <li><strong>Import data set using pandas</strong></li> <li>Manipulate data</...
<p>Fellow newbie here! Try removing the "../" from your data location</p> <p>Change</p> <pre><code>data = pd.read_csv("../data/walmart-stores.csv") </code></pre> <p>to </p> <pre><code>data = pd.read_csv("data/walmart-stores.csv") </code></pre>
python|csv|pandas|matplotlib|jupyter-notebook
0
39
44,144,538
Find values in numpy array space-efficiently
<p>I am trying to create a copy of my numpy array that contains only certain values. This is the code I was using:</p> <pre><code>A = np.array([[1,2,3],[4,5,6],[7,8,9]]) query_val = 5 B = (A == query_val) * np.array(query_val, dtype=np.uint16) </code></pre> <p>... which does exactly what I want.</p> <p>Now, I'd like...
<p>Here's one approach using <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer"><code>np.searchsorted</code></a> -</p> <pre><code>def mask_in(a, b): idx = np.searchsorted(b,a) idx[idx==b.size] = 0 return np.where(b[idx]==a, a,0) </code></...
python|numpy
0
40
69,371,270
tensorflow.python.framework.errors_impl.AlreadyExistsError
<p>I trained a ImageClassifier model using <a href="https://teachablemachine.withgoogle.com/train/image" rel="nofollow noreferrer">Teachable Machine</a> and I tried to run the following code on VScode in python 3.8</p> <pre><code>from keras.models import load_model from PIL import Image, ImageOps import numpy as np # ...
<p>To run this code , You need to use</p> <pre><code>from tensorflow.keras.models import load_model </code></pre> <p>in place of</p> <pre><code>from keras.models import load_model </code></pre> <p>This issue comes due to mismatch of <code>tensorflow</code> and <code>keras</code> version available in your system. Make s...
python|tensorflow|keras|image-classification
0
41
69,414,137
Parsing (from text) a table with two-row header
<p>I'm parsing the output of a .ipynb. The output was generated as plain text (using print) instead of a dataframe (not using print), in the spirit of:</p> <pre><code>print( athletes.groupby('NOC').count() ) </code></pre> <p>I came up with hacks (e.g. using <code>pandas.read_fwf()</code>) to the various cases, but I wa...
<p>Assuming the following input:</p> <pre><code>text = ''' Name Discipline NOC United States of America 615 615 Japan 586 586 Australia 470 470 People's Republic of China 401 ...
python|pandas|jupyter-notebook
1
42
69,488,329
Apply fuzzy ratio to two dataframes
<p>I have two dataframes where <strong>I want to fuzzy string compare &amp; apply my function to two dataframes</strong>:</p> <pre><code>sample1 = pd.DataFrame(data1.sample(n=200, random_state=42)) sample2 = pd.DataFrame(data2.sample(n=200, random_state=13)) def get_ratio(row): sample1 = row['address'] sample2...
<p>You need to create the permutations of your addresses. Then use that to compare the matching ones. You can find a similar question <a href="https://stackoverflow.com/questions/68978444/how-to-do-fuzzy-match-merge-to-match-based-on-a-few-columns/68979157#68979157">here</a>.</p> <p>For your case first you need to crea...
python|python-3.x|pandas|function|fuzzywuzzy
1
43
69,431,754
How can I reshape a Mat to a tensor to use in deep neural network in c++?
<p>I want to deploy a trained deep neural network in c++ application. After reading image and using blobFromImage( I used opencv 4.4 ) function I received the blew error which is indicate I have problem with dimensions and shape of my tensor. The input of deep neural network is (h=150, w=100, channel=3). Is blobFromIma...
<p>The following code works for me. The only difference is that I'm loading tensorflow model.</p> <pre><code>inputNet = cv::dnn::readNetFromTensorflow(pbFilePath); // load image of rowsxcols = 160x160 cv::Mat img, imgn, blob; img = cv::imread(&quot;1.jpg&quot;); //cv::cvtColor(img, img, CV_GRAY2RGB);// convert gray to ...
c++|tensorflow|opencv|deep-learning|neural-network
-1
44
69,318,826
Tensorflow Object-API: convert ssd model to tflite and use it in python
<p>I have a hard time to convert a given tensorflow model into a tflite model and then use it. I already posted a <a href="https://stackoverflow.com/questions/69305190/object-detection-with-tflite">question</a> where I described my problem but didn't share the model I was working with, because I am not allowed to. Sinc...
<p>For the models from Object Detection APIs to work well with TFLite, you have to convert it to TFLite-friendly graph that has custom op.</p> <p><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md" rel="nofollow noreferrer">https://github.com/tensorflow/mo...
tensorflow|computer-vision|tensorflow-lite|object-detection-api|single-shot-detector
1
45
53,834,223
Comparing a `tf.constant` to an integer
<p>In TensorFlow, I have a <code>tf.while_loop</code>, where the <code>body</code> argument is defined as the following function:</p> <pre><code>def loop_body(step_num, x): if step_num == 0: x += 1 else: x += 2 step_num = tf.add(step_num, 1) return step_num, x </code></pre> <p>The prob...
<p>First approach: using <code>tf.cond</code>:</p> <pre><code>def loop_body(step_num, x): x = tf.cond(tf.equal(step_num,0),lambda :x+1,lambda :x+2) step_num = tf.add(step_num, 1) return step_num, x </code></pre> <p>Second approach: using <code>autograph</code>:</p> <pre><code>from tensorflow.contrib impo...
python|tensorflow
3
46
54,061,940
How to match a column entry in pandas against another similar column entry in a different row?
<p>Say for a given table :</p> <pre><code>d.DataFrame([['Johnny Depp', 'Keanu Reeves'], ['Robert De Niro', 'Nicolas Cage'], ['Brad Pitt', 'Johnny Depp'], ['Leonardo DiCaprio', 'Morgan Freeman'], ['Tom Cruise', 'Hugh Jackman'], ['Morgan Freeman', 'Robert ...
<p>First, you make a list with all the actors' names.</p> <pre><code>actors = ['Johnny Depp', 'Keanu Reeves', 'Robert De Niro', 'Nicolas Cage', 'Brad Pitt', 'Johnny Depp', 'Leonardo DiCaprio', 'Morgan Freeman', 'Tom Cruise', 'Hugh Jackman', 'Morgan Freeman', 'Robert De Niro', ] </code></p...
python|pandas
0
47
54,096,827
ValueError: Plan shapes are not aligned
<p>I have four data frames that are importing data from different excel files ( Suppliers) and I am trying to combine these frames. When I include df3 when concatenating I get an error. I referred a lot of articles on similar error but not getting clue. </p> <p>I tried upgrading pandas. Tried the following code as wel...
<p>It worked after entering the following code</p> <p>data3['Quantity'] = data3['Quantity'].replace(" ","")</p>
python|pandas
0
48
53,866,744
Weighted mean in pandas - string indices must be integers
<p>I am going to calculate weighted average based on csv file. I have already loaded columns: A, B which contains float values. My csv file:</p> <pre><code>A B 170.804 2854 140.924 510 164.842 3355 </code></pre> <p>Pattern</p> <pre><code>(w1*x1 + w2*x2 + ...) / (w1 + w2 + w3 + ...) </code></pre> <p>My code:</p> ...
<p>IIUC, you might try this (the line of code you wrote should work as well):</p> <pre><code>wa = df['A'].dot(df['B']) / df['B'].sum() print(wa) 165.55897693109094 </code></pre>
python|pandas
0
49
53,904,155
Flexibly select pandas dataframe rows using dictionary
<p>Suppose I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]}) brand color year 0 Ford red 2016 1 fiat green 2016 2 opel blue 2017 </code></pre> <p>I know that to...
<p>With single expression:</p> <pre><code>In [728]: df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]}) In [729]: d = {'color':'red', 'year':2016} In [730]: df.loc[np.all(df[list(d)] == pd.Series(d), axis=1)] Out[730]: brand color year 0 Ford red 20...
python|python-3.x|pandas|dataframe|select
2
50
54,058,953
Storing more than a million .txt files into a pandas dataframe
<p>I have a set of more than million records all of them in the <code>.txt</code> format. Each <code>file.txt</code> has just one line:</p> <blockquote> <p>'user_name', 'user_nickname', 24, 45</p> </blockquote> <p>I need to run a distribution check on the aggregated list of numeric features from the million files. ...
<p>The following code cuts the processing time to 10,000 files a minute. This is an implementation of the suggestion from @DYZ <a href="https://stackoverflow.com/questions/54058953/storing-more-than-a-million-txt-files-into-a-pandas-dataframe?noredirect=1#comment94951786_54058953">here</a>.</p> <pre><code>import csv, ...
python|pandas|sqlite
2
51
54,192,420
How to use melt function in pandas for large table?
<p>I currently have data which looks like this: </p> <pre><code> Afghanistan_co2 Afghanistan_income Year Afghanistan_population Albania_co2 1 NaN 603 1801 3280000 NaN 2 NaN 603 1802 3280000 NaN 3 NaN 603 1803 3280000 NaN 4 NaN 603 1804 3280000 NaN </code></pre> <p>and I would like to use m...
<p>Just doing with <code>str.split</code> with your columns</p> <pre><code>df.set_index('Year',inplace=True) df.columns=pd.MultiIndex.from_tuples(df.columns.str.split('_').map(tuple)) df=df.stack(level=0).reset_index().rename(columns={'level_1':'Country'}) df Year Country co2 income population 0 1801 Afgh...
python|pandas
1
52
38,401,845
Scipy.linalg.logm produces an error where matlab does not
<p>The line <code>scipy.linalg.logm(np.diag([-1.j, 1.j]))</code> produces an error with scipy 0.17.1, while the same call to matlab, <code>logm(diag([-i, i]))</code>, produces valid output. I already filed a <a href="https://github.com/scipy/scipy/issues/6378" rel="nofollow">bugreport on github</a>, now I am here to as...
<p>I don't know enough about the calculation to understand the error. But it has something to do division by zero - probably in the real part.</p> <p>Replacing the zero real part of the array with a small value works:</p> <pre><code>In [40]: linalg.logm(np.diag([1e-16-1.j,1e-16+1.j])) Out[40]: array([[ 5.00000000e...
python|matlab|numpy|scipy
1
53
38,156,023
Properly shifting irregular time series in Pandas
<p>What's the proper way to shift this time series, and re-align the data to the same index? E.g. How would I generate the data frame with the same index values as "data," but where the value at each point was the last value seen as of 0.4 seconds after the index timestamp?</p> <p>I'd expect this to be a rather common...
<p>Just like on <a href="https://stackoverflow.com/q/38131287/478288">this question</a>, you are asking for an asof-join. Fortunately, the next release of pandas (soon-ish) will have it! Until then, you can use a pandas Series to determine the value you want.</p> <p>Original DataFrame:</p> <pre><code>In [44]: data Ou...
python|pandas
3
54
65,931,302
I am trying to use CNN for stock price prediction but my code does not seem to work, what do I need to change or add?
<pre><code>import math import numpy as np import pandas as pd import pandas_datareader as pdd from sklearn.preprocessing import MinMaxScaler from keras.layers import Dense, Dropout, Activation, LSTM, Convolution1D, MaxPooling1D, Flatten from keras.models import Sequential import matplotlib.pyplot as plt df = pdd.DataR...
<p>Your model doesn't tie to your data.</p> <p>Change this line:</p> <pre><code>model.add(Convolution1D(64, 3, input_shape= (60,1), padding='same')) </code></pre>
python|tensorflow|keras|conv-neural-network
0
55
65,950,088
randomly choose different sets in numpy?
<p>I am trying to randomly select a set of integers in numpy and am encountering a strange error. If I define a numpy array with two sets of different sizes, <code>np.random.choice</code> chooses between them without issue:</p> <pre><code>Set1 = np.array([[1, 2, 3], [2, 4]]) In: np.random.choice(Set1) Out: [4, 5] </co...
<p>Your issue is caused by a misunderstanding of how numpy arrays work. The first example can not &quot;really&quot; be turned into an array because numpy does not support ragged arrays. You end up with an array of object references that points to two python lists. The second example is a proper 2xN numerical array. I ...
python|numpy|sampling
2
56
52,571,930
Selecting vector of 2D array elements from column index vector
<p>I have a 2D array A:</p> <pre><code>28 39 52 77 80 66 7 18 24 9 97 68 </code></pre> <p>And a vector array of column indexes B:</p> <pre><code>1 0 2 0 </code></pre> <p>How, in a pythonian way, using base Python or Numpy, can I select the elements from A which DO NOT correspond to the co...
<p>You can make use of broadcasting and a row-wise mask to select elements not contained in your array for each row:</p> <p><strong><em>Setup</em></strong></p> <pre><code>B = np.array([1, 0, 2, 0]) cols = np.arange(A.shape[1]) </code></pre> <hr> <p>Now use broadcasting to create a mask, and index your array.</p> <...
python|arrays|numpy
2
57
52,808,604
subtracting strings in array of data python
<p>I am trying to do the following:</p> <ol> <li>create an array of random data</li> <li>create an array of predefined codes (AW, SS)</li> <li>subtract all numbers as well as any instance of predefined code. </li> <li>if a string called "HL" remains after step 3, remove that as well and take the next alphabet pair. If...
<p>This is fairly simple using Regex.</p> <p><code>re.findall(r'[A-Z].',item)</code> should give you the text from your strings, and then you can do the required processing on that.</p> <p>You may want to convert the list to a set eventually and use the <code>difference</code> operation, instead of looping and removi...
python|arrays|regex|pandas|loops
1
58
46,312,675
What's the LSTM model's output_node_names?
<p>all. I want generate a freezed model from one LSTM model (<a href="https://github.com/roatienza/Deep-Learning-Experiments/tree/master/Experiments/Tensorflow/RNN" rel="nofollow noreferrer">https://github.com/roatienza/Deep-Learning-Experiments/tree/master/Experiments/Tensorflow/RNN</a>). In my option, I should freeze...
<p>As mentioned above, "lstm_prediction" is output_node_name. And Tensorboard help me a lot to understand the graph.</p>
tensorflow|freeze|lstm
0
59
46,209,772
Discrepancy of the state of `numpy.random` disappears
<p>There are two python runs of the same project with different settings, but with the same random seeds.</p> <p>The project contains a function that returns a couple of random numbers using <code>numpy.random.uniform</code>.</p> <p>Regardless of other uses of <code>numpy.random</code> in the python process, series o...
<p>When you use the <code>random</code> module in numpy, each randomly generated number (regardless of the distribution/function) uses the same "global" instance of <code>RandomState</code>. When you set the seed using <code>numpy.random.seed()</code>, you set the seed of the 'global' instance of <code>RandomState</cod...
python|numpy-random
0
60
68,965,218
Remove duplicate strings within a pandas dataframe entry
<p>I need to remove duplicate strings within a pandas dataframe entry. But Im only find solutions for removing duplicate rows.</p> <p>The entries I want to clean look like this:</p> <p><a href="https://i.stack.imgur.com/JZhtQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JZhtQ.png" alt="enter image...
<p>Try this (I've added a simple example of my own df):</p> <pre><code>import pandas as pd data = ['a,b,c','a,b,b,e,d','a,a,e,d,f'] df = pd.DataFrame(data,columns={&quot;cleaned_data&quot;}) def remove_dups_letters(row): sentences = set(row.split(&quot;,&quot;)) new_str = ','.join(sentences) return new_st...
python|pandas|dataframe
1
61
69,254,771
Parallelize a function with multiple inputs/outputs geodataframe-variables
<p>Using a previous answer (merci Booboo), The code idea is:</p> <pre><code>from multiprocessing import Pool def worker_1(x, y, z): ... t = zip(list_of_Polygon,list_of_Point,column_Point) return t def collected_result(t): x, y, z = t # unpack save_shp(&quot;polys.shp&quot;,x) save_shp(&quot;point....
<p>Well, if I understand what you are trying to do, perhaps the following is what you need. Here I am building up the <code>args</code> list that will be used as the <em>iterable</em> argument to <code>starmap</code> by iterating on <code>gg.iterrows()</code> (there is no need to use <code>zip</code>):</p> <pre class="...
python|parallel-processing|geopandas|pool|shapely
0
62
69,229,971
Arange ordinal number for range of values in column
<p>So I have some kind of data frame which, and in one column values range from 139 to 150 (rows with values repeat). How to create new column, which will assign ordinal value based on the mentioned column? For example, 139 -&gt; 0, 140 -&gt; 1, ..., 150 -&gt; 10</p> <p>UPD: Mozway's answer is suitable, thanks!</p>
<p>Simply subtract 139: <code> df['col'] -= 139</code></p> <p>Or, to get a new column: <code>df['new'] = df['col'] - 139</code></p>
python|pandas|dataframe
1
63
60,948,086
Creating a function that operates different string cleaning operations
<p>I built a function that performs multiple cleaning operations, but when I run it on an object column, I get the AttributeError: 'str' object has no attribute 'str' error. Why is that?</p> <pre><code>news = {'Text':['bNikeb invests in shoes', 'bAdidasb invests in t-shirts', 'dog drank water'], 'Source':['NYT', 'WP',...
<pre><code>news = {'Text':['bNikeb invests in shoes', 'bAdidasb invests in t-shirts', 'dog drank water'], 'Source':['NYT', 'WP', 'Guardian']} news_df = pd.DataFrame(news) def string_cleaner(x): x = x.strip() x = x.replace('.', '') x = x.replace(' ', '') return x news_df['clean'] = news_df['Text'].appl...
python|string|pandas|function
1
64
60,820,941
How to break down a numpy array into a list and create a dictionary?
<p>I have a following list and a numpy array : For the list :</p> <pre><code>features = np.array(X_train.columns).tolist() results : ['Attr1', 'Attr2', 'Attr3', 'Attr4', 'Attr5', 'Attr6', 'Attr7', 'Attr8', 'Attr9', 'Attr10', 'Attr11', 'Attr12', 'Attr13', 'Attr14', 'Attr15', 'Attr16', 'Attr17', 'Attr18', 'Attr19', ...
<p>you could use the built-in function <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer">zip</a> :</p> <pre><code>dict(zip(features, ab[0].ravel())) </code></pre> <p>you can check the docs for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html#numpy.r...
python|numpy
1
65
71,476,405
Mapping values from one Dataframe to another and updating existing column
<p>I have a dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td>10</td> </tr> <tr> <td>2</td> <td>Mary</td> <td>10</td> </tr> <tr> <td>3</td> <td>Tom</td> <td>9</td> </tr> <tr> <td>4</td> <td...
<p>Does this suffice:</p> <pre class="lang-py prettyprint-override"><code>df1.set_index('Id').fillna({'Name' : df2.set_index('Id').Name}).reset_index() Id Name Score 0 1 John 10 1 2 Mary 10 2 3 Tom 9 3 4 Jerry 8 4 5 Pat 7 </code></pre>
python|pandas
0
66
43,086,557
Convolve2d just by using Numpy
<p>I am studying image-processing using NumPy and facing a problem with filtering with convolution.</p> <p><strong>I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)</strong></p> <p>Does anyone have an idea to <strong>refine</strong> my method?</p> <p>I know that <a href="https:/...
<p>You could generate the subarrays using <a href="https://stackoverflow.com/questions/19414673/in-numpy-how-to-efficiently-list-all-fixed-size-submatrices"><code>as_strided</code></a>:</p> <pre><code>import numpy as np a = np.array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], ...
python|numpy|image-processing|matrix|convolution
34
67
72,426,602
Concat two values into string Pandas?
<p>I tried to concat two values of two columns in Pandas like this:</p> <pre><code>new_dfr[&quot;MMYY&quot;] = new_dfr[&quot;MM&quot;]+new_dfr[&quot;YY&quot;] </code></pre> <p>I got warning message:</p> <pre><code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc...
<pre><code>new_dfr[&quot;MMYY&quot;] = new_dfr[&quot;MM&quot;].astype(str) + new_dfr[&quot;YY&quot;].astype(str) </code></pre>
pandas
0
68
72,413,201
Is there a faster way to do this loop?
<p>I want to create a new column using the following loop. The table just has the columns 'open', and 'start'. I want to create a new column 'startopen', where if 'start' equals 1, then 'startopen' is equal to 'open'. Otherwise, 'startopen' is equal to whatever 'startopen' was in the row above of this newly created col...
<blockquote> <p>I want to create a new column 'startopen', where if 'start' equals 1, then 'startopen' is equal to 'open'</p> <p>Otherwise, 'startopen' is equal to whatever 'startopen' was in the row above of this newly created column.</p> </blockquote> <p>IIUC, otherwise part is equal to forward fill the not 1 <code>s...
python|pandas
2
69
72,360,949
Aggregating multiple columns Pandas
<p>Currently my csv looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>title</th> <th>field1</th> <th>field2</th> <th>field3</th> <th>field4</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>A1</td> <td>A11</td> <td>553</td> <td>0</td> </tr> <tr> <td>A</td> <td>A1</td> <td>A12</...
<p>Use:</p> <pre><code>def fun(df, cols_to_aggregate, cols_order): df = df.groupby(['field1', 'field2'], as_index=False)\ .agg(cols_to_aggregate) df['title'] = 'A' #aggregate field4 to new column df['field4'] = df.groupby('field1')['field4'].transform('sum') df = df[cols_order] r...
python|pandas|csv
2
70
72,186,132
TypeError: 'module' object is not callable when using Keras
<p>I've been having lots of imports issues when it comes to TensorFlow and Keras and now I stumbled upon this error:</p> <pre><code>TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_17880/703187089.py in &lt;module&gt; 75 #model.compile(loss=&quot;categorica...
<p><code>kerns.optimizers.rmsprop_v2</code> and <code>kerns.optimizers.adadelta_v2 </code> are the modules. You want:</p> <pre><code>from keras.optimizers import RMSprop, Adadelta </code></pre> <p>And:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/RMSprop" rel="nofollow noreferrer"><cod...
python|tensorflow|keras
1
71
72,396,287
Sort pandas Series both on values and index
<p>I want to sort a Series in descending by value but also I need to respect the alphabetical order of the index. Suppose the Series is like this:</p> <pre><code>(index) a 2 b 5 d 3 z 1 t 1 g 2 n 3 l 6 f 6 f 7 </code></pre> <p>I need to con...
<p>You can first sort the index, then sort the values with a stable algorithm:</p> <pre><code>s.sort_index().sort_values(ascending=False, kind='stable') </code></pre> <p>output:</p> <pre><code>f 7 l 6 b 5 d 3 n 3 a 2 g 2 t 1 z 1 dtype: int64 </code></pre> <p>used input:</p> <pre><code>s = pd....
python|pandas|sorting|series|numpy-ndarray
1
72
50,540,768
Tensorflow linear regression house prices
<p>I am trying to solve a linear regression problem using neural networks but my loss is coming to the power of 10 and is not reducing for training. I am using the house price prediction dataset(<a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques" rel="nofollow noreferrer">https://www.kaggle.c...
<p>You are simple randomly initializing the variables in every training step. Just call <code>sess.run(tf.global_variables_initializer())</code> only once before the loop. </p>
tensorflow|linear-regression
1
73
50,242,364
Multiple Aggregate Functions based on Multiple Columns in Pandas
<p>I am working with a Pandas df in Python. I have the following input df:</p> <pre><code>Color Shape Value Blue Square 5 Red Square 2 Green Square 7 Blue Circle 9 Blue Square 2 Green Circle 6 Red Circle 2 Blue Square 5 Blue Circle 1 </code></pre> <p>I would like the following...
<p>OK, so I did more research and will answer this one myself, because it may be helpful for others.</p> <p>The problem I am having is associated with indexing more than pivot tables. To remove the multiple index a simple: </p> <pre><code>df.reset_index() </code></pre> <p>does the trick just fine.</p> <p>As a side...
python|pandas|pivot-table
1
74
50,383,480
Adding a pickle-able attribute to a subclass of numpy.ndarray
<p>I would like to add a property (<code>.csys</code>) to a subclass of numpy.ndarray:</p> <pre><code>import numpy as np class Point(np.ndarray): def __new__(cls, arr, csys=None): obj = np.asarray(arr, dtype=np.float64).view(cls) obj._csys = csys return obj def __array_finalize__(sel...
<p>This question has already been asked and answered <a href="https://stackoverflow.com/questions/26598109/preserve-custom-attributes-when-pickling-subclass-of-numpy-array">here</a>. In a nutshell, numpy uses <code>__reduce__</code> and <code>__setstage__</code> to pickle itself. The overrides, adapted to the case abov...
python-3.x|numpy|pickle
0
75
45,599,988
Looking for help on installing a numpy extension
<p>I found a numpy extension on github that would be really helpful for a program I'm currently writting, however I don't know how to install it.</p> <p>Here's the link to the extension: <a href="https://pypi.python.org/pypi?name=py_find_1st&amp;:action=display" rel="nofollow noreferrer">https://pypi.python.org/pypi?n...
<p>To build any extension modules for Python, you’ll need a <code>C compiler</code>. Various <code>NumPy</code> modules use <code>FORTRAN 77</code> libraries, so you’ll also need a <code>FORTRAN 77</code> compiler installed.</p> <p>However, if you just want to install the tar.gz file that they have on the website, fol...
python|python-3.x|numpy
1
76
62,709,674
How to split a dataframe heaving a list of column values and counts?
<p>I have a CSV based dataframe</p> <pre><code>name value A 5 B 5 C 5 D 1 E 2 F 1 </code></pre> <p>and a values count dictionary like this:</p> <pre><code>{ 5: 2, 1: 1 } </code></pre> <p>How to split original dataframe into two:</p> <pre><code>name value A 5 B 5 D ...
<p>This worked for me:</p> <pre><code>def target_indices(df, value_count): indices = [] for index, row in df.iterrows(): for key in value_count: if key == row['value'] and value_count[key] &gt; 0: indices.append(index) value_count[key] -= 1 return(indices)...
python|pandas
1
77
62,704,351
sentiment analysis using python pandas and scikit learn
<p>I have a dataset of product review.I want to count words in a way that instead of counting all the words I want to count some specific words like ('Amazing','Great','Love' etc) and put this counting in a column called 'word_count'.Now our goal is to create a column products[‘awesome’] where each row contains the num...
<p>Alright I lied; for standalone getting word frequency over a corpus we can combine pandas and numpy like so:</p> <pre><code>word_A = np.array(df.series.str.findall('word')) getlength = np.vectorize(len) getlength(word_A) </code></pre> <p><em><strong>Whats going on under the hood:</strong></em></p> <p><strong>LINE1</...
python|pandas|scikit-learn|sentiment-analysis
0
78
62,576,811
Need help in debugging Shallow Neural network using numpy
<p>I'm doing a hands-on for learning and have created a model in python using numpy that's being trained on breast cancer dataSet from sklearn library. Model is running without any error and giving me Train and Test accuracy as 92.48826291079813% and 90.9090909090909% respectively. However somehow I'm not able to compl...
<p>I figured out where the problem was. It was the third line in predict function where I was reshaping bias which was not at all necessary.</p> <pre><code>def predict(X, parameters): W = parameters[&quot;W&quot;] b = parameters[&quot;b&quot;] **b = b.reshape(b.shape[0],1)** Z = np.dot(W.T,X) + b Y = np.array...
python|numpy|neural-network
0
79
62,637,487
Numpy Histogram over very tiny floats
<p>I have an array with small float numbers, here is an exempt:</p> <pre><code>[-0.000631510156545283, 0.0005999252334386763, 2.6784775066479167e-05, -6.171351407584846e-05, -2.0256783283654057e-05, -5.700196588437318e-05, 0.0006830172130385885, -7.862102776837944e-06, 0.0008167604859504389, 0.0004497656945683915, -...
<p>For other people looking for an answer:</p> <p>As Jody Klymak suggested in a comment to my question, manually specify the bins. I did not need to preprocess the data further, as I thought I had to do.</p> <p>Example:</p> <pre><code>import matplotlib.pyplot as plt import bumpy as np array = [...] # large array with ...
python|numpy|matplotlib|histogram
1
80
62,826,624
Change bar colors in pandas matplotlib bar chart by passing a list/tuple
<p>There are several threads on this topic, but none of them seem to directly address my question. I would like to plot a bar chart from a pandas dataframe with a custom color scheme that does not rely on a map, e.g. use an arbitrary list of colors. It looks like I can pass a concatenated string with color shorthand na...
<p>When plotting a dataframe, the first color information is used for the first column, the second for the second column etc. Color information may be just one value that is then used for all rows of this column, or multiple values that are used one-by-one for each row of the column (repeated from the beginning if more...
python|pandas|matplotlib
3
81
54,519,021
How to compute hash of all the columns in Pandas Dataframe?
<p><code>df.apply</code> is a method that can apply a certain function to all the columns in a dataframe, or the required columns. However, my aim is to compute the hash of a string: this string is the concatenation of all the values in a row corresponding to all the columns. My current code is returning <code>NaN</cod...
<p>You can create a new column, which is concatenation of all others:</p> <pre><code>df['new'] = df.astype(str).values.sum(axis=1) </code></pre> <p>And then apply your hash function on it</p> <pre><code>df["row_hash"] = df["new"].apply(self.hash_string) </code></pre> <p>or this one-row should work:</p> <pre><code>...
python|python-3.x|pandas
4
82
73,713,141
Why does all my emission mu of HMM in pyro converge to the same number?
<p>I'm trying to create a Gaussian HMM model in pyro to infer the parameters of a very simple Markov sequence. However, my model fails to infer the parameters and something wired happened during the training process. Using the same sequence, hmmlearn has successfully infer the true parameters.</p> <p>Full code can be a...
<p>I have not tried this model, but I think it should be possible to solve the problem by modifying the model in the following way: def model(observations, num_state):</p> <pre><code>assert not torch._C._get_tracing_state() with poutine.mask(mask = True): p_transition = pyro.sample(&quot;p_transition&quot;, ...
machine-learning|pytorch|statistics|artificial-intelligence|pyro
0
83
73,553,937
How to aggregate of a datetime dataframe based on days and then how to calculate average?
<p>I have a dataframe with two columns, date and values.</p> <pre><code>import numpy as np import pandas as pd import datetime from pandas import Timestamp a = [[Timestamp('2014-06-17 00:00:00'), 0.023088847378082145], [Timestamp('2014-06-18 00:00:00'), -0.02137513226556209], [Timestamp('2014-06-19 00:00:00'), -0.0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>DataFrame.resample</code></a> with aggregate <code>mean</code> by <code>5D</code> for 5 days:</p> <pre><code>df = df.resample('5D', on='dates')['Values'].mean().reset_index() </code>...
python|pandas|dataframe|datetime
4
84
73,755,801
how to show pandas data frame data as bar graph?
<p>how to show pandas data frame data as bar graph?</p> <p>I have the data like below,</p> <pre><code>[{'index': 0, 'Year_Week': 670, 'Sales_CSVolume': 10}, {'index': 1, 'Year_Week': 680, 'Sales_CSVolume': 8}, {'index': 2, 'Year_Week': 700, 'Sales_CSVolume': 4}, {'index': 3, 'Year_Week': 850, 'Sales_CSVolume': 13}] <...
<pre><code>import pandas as pd import seaborn as sns data = [{'index': 0, 'Year_Week': 670, 'Sales_CSVolume': 10}, {'index': 1, 'Year_Week': 680, 'Sales_CSVolume': 8}, {'index': 2, 'Year_Week': 700, 'Sales_CSVolume': 4}, {'index': 3, 'Year_Week': 850, 'Sales_CSVolume': 13}] df = pd.DataFrame(data) df.set_index('inde...
python|pandas|matplotlib
1
85
71,358,446
Pandas DataFrame subtraction is getting an unexpected result. Concatenating instead?
<p>I have two dataframes of the same size (510x6)</p> <pre><code>preds 0 1 2 3 4 5 0 2.610270 -4.083780 3.381037 4.174977 2.743785 -0.766932 1 0.049673 0.731330 1.656028 -0.427514 -0.803391 -0.656469 2 -3.5793...
<p>There are many ways that two different values can appear the same when displayed. One of the main ways is if they are different types, but corresponding values for those types. For instance, depending on how you're displaying them, the int <code>1</code> and the str <code>'1'</code> may not be easily distinguished. ...
pandas|dataframe|python-3.7|subtraction
0
86
71,252,285
Group date column into n-day periods
<p>I need a function that groups date column into n-day periods with respect to some start and end dates (1 year interval). To assign a quarter (~90 day period) to every date in the data frame I used the code below, which is not very neat (and I want to reuse it for 30-day period as well)</p> <pre><code>def get_quarter...
<p>FTR, a possible solution is to shift every date in the series according to the <code>start_date</code>, to simulate that <code>start_date</code> is the beginning of the year:</p> <pre><code>&gt;&gt;&gt; start_date = pd.to_datetime(&quot;2021-06-16&quot;) &gt;&gt;&gt; dates_series = pd.Series([pd.to_datetime(&quot;20...
python-3.x|pandas|dataframe|date|pandas-groupby
1
87
72,780,603
Format pandas dataframe output into a text file as a table (formatted and aligned to the max length of the data or header (which ever is longer))
<pre><code>pd.DataFrame({ 'ID': { 0: 11404371006, 1: 11404371007, 2: 11404371008, 3: 11404371009, 4: 11404371010, 5: 11404371011 }, 'TABLE.F1': { 0: 'Y', 1: 'NULL', 2: 'N', 3: ...
<p>Use <code>to_markdown</code>:</p> <pre><code>out = df.to_markdown(index=False, tablefmt='pipe', colalign=['center']*len(df.columns)) print(out) # Output: | ID | TABLE.F1 | O | |:-----------:|:----------:|:-----:| | 11404371006 | Y | False | | 11404371007 | NULL | False | | 11404371008 ...
python|pandas|dataframe
3
88
72,672,399
dataframe.str[start:stop] where start and stop are columns in same data frame
<p>I would like to use pandas.str to vectorize slice operation on pandas column which values are list and start and stop values are int values in start and stop columns of same dataframe example:</p> <pre><code>df['column_with_list_values'].str[start:stop] df[['list_values', 'start', 'stop']] list_valu...
<pre><code>df.apply(lambda x: x.list_values[x.start:x.stop], axis=1) </code></pre> <p>Output:</p> <pre><code>0 [5, 7] 1 [3, 5] 2 [1, 3] 3 [1, 3] 4 [3, 5] 5 [5, 7] 6 [1, 3] dtype: object </code></pre> <hr /> <p>I'm not sure why, but the fastest variation appears to be:</p> <pre><code>df['sliced'] = ...
python|pandas
2
89
72,583,548
How to find row index which contains given string? Python
<p>I would like to upgrade my scrip to analyze data. Instead of manualy checking row number to be header line i need to find the index row that contains specific string. Now i read csv directly to pandas dataframe with headerline defined like this:</p> <pre><code>df1 = pd.read_csv('sensor_1.csv', sep=',', header=101) <...
<pre><code>fille_ = open('sensor_1.csv', 'r') lines = fille_.readlines() cnt = 0 for i in range(0, len(lines)): if lines[i].find('Scan Number') !=-1: cnt = i break print(cnt) </code></pre> <p>When the search phrase is found in the string, the loop will print the index of the string and the...
python|pandas
1
90
59,477,254
Replacing states with country name pandas
<p>Is there a way to change state abbreviations into "USA" in a data frame :</p> <pre><code>'CIBA GEIGY CORP,BASIC PHARMACEUT RES,ARDSLEY,NY 10502' </code></pre> <p>to </p> <pre><code>'CIBA GEIGY CORP,BASIC PHARMACEUT RES,ARDSLEY,USA 10502' </code></pre> <p>I tried with a dictionary: <code>df.Authors.str.translate(...
<p>I think you can just use <code>df.replace</code> (works for <code>pd.Series</code> too):</p> <p><code>df['Authors'].replace(us_states, inplace=True, regex=True)</code>.</p> <p>Documentation here: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow norefe...
python|python-3.x|pandas
1
91
40,352,841
How can I build a TF Graph that has separate inference and training parts?
<p>Referencing <a href="https://stackoverflow.com/questions/40340807/how-can-i-build-a-tf-graph-for-both-training-and-inference-with-tf-train-shuffle">this post</a> asked previously, as the suggestion was to create a graph that has separate inference and training parts.</p> <p>Boilerplate code would be greatly appreci...
<p>MNIST convolution in the repository is an example -- <a href="https://github.com/tensorflow/tensorflow/blob/8e48ec6ea0492e2cb9fd19c0a2ccf41afc7b4dc6/tensorflow/models/image/mnist/convolutional.py" rel="nofollow">tensorflow/tensorflow/models/image/mnist/convolutional.py</a></p> <p>It follows a pattern when you facto...
tensorflow
2
92
40,587,902
Function to select from columns pandas df
<p>i have this test table in pandas dataframe</p> <pre><code> Leaf_category_id session_id product_id 0 111 1 987 3 111 4 987 4 111 1 741 1 222 2 654 2 333 3 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> first and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> ...
python|pandas|numpy
1
93
40,386,175
Python: convert string array to int array in dataframe
<p>I have a data frame, duration is one of the attributes. The duration's content is like: </p> <pre><code> array(['487', '346', ..., '227', '17']). </code></pre> <p>And the df.info(), I get: Data columns (total 22 columns):</p> <pre><code> duration 2999 non-null object c...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><code>astype</code></a>:</p> <pre><code>df['duration'] = df['duration'].astype(int) </code></pre> <p><strong>Timings</strong></p> <p>Using the following setup to produce a large sample dataset:<...
python|pandas|numpy
4
94
40,635,718
Pandas merge column where between dates
<p>I have two dataframes - one of calls made to customers and another identifying active service durations by client. Each client can have multiple services, but they will not overlap. </p> <pre><code>df_calls = pd.DataFrame([['A','2016-02-03',1],['A','2016-05-11',2],['A','2016-10-01',3],['A','2016-11-02',4], ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with left join:</p> <pre><code>print (pd.merge(df_calls, df_calls2, how='left')) cust_id call_date call_id service_id 0 A 2016-02-03 1 1.0 1 ...
python|pandas
3
95
40,471,883
Split column and format the column values
<p>I am trying to format one column data. I can find options to split the columns as it has <code>,</code> in between but I am not able to format it as shown in output. </p> <p>Input </p> <pre><code> TITLE,Issn NATURE REVIEWS MOLECULAR CELL BIOLOGY,"ISSN 14710072, 14710080" ANNUAL REVIEW OF IMMUNOLOGY,"ISSN 073205...
<p>IIUC you can do it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer">Series.str.extract()</a>, <code>apply()</code> and <code>replace()</code> methods:</p> <pre><code>In [33]: df Out[33]: TITLE ...
python|csv|pandas|dataframe|data-cleaning
2
96
61,879,043
Remove NaN values from pandas dataframes inside a list
<p>I have a number of dataframes inside a list. I am trying to remove NaN values. I tried to do it in a for loop:</p> <pre><code>for i in list_of_dataframes: i.dropna() </code></pre> <p>it didn't work but python didnt return an error neither. If I apply the code </p> <pre><code>list_of_dataframes[0] = list_of_da...
<p>You didn't assign the new DataFrames with the dropped values to anything, so there was no effect.</p> <p>Try this:</p> <pre class="lang-py prettyprint-override"><code>for i in range(len(list_of_dataframes)): list_of_dataframes[i] = list_of_dataframes[i].dropna() </code></pre> <p>Or, more conveniently:</p> <p...
pandas|nested-lists|nested-datalist
0
97
61,727,806
Concatenate alternate scalar column to pandas based on condition
<p>Have a <code>master</code> dataframe and a <code>tag</code> list, as follows:</p> <pre><code>import pandas as pd i = ['A'] * 2 + ['B'] * 3 + ['A'] * 4 + ['B'] * 5 master = pd.DataFrame(i, columns={'cat'}) tag = [0, 1] </code></pre> <p>How to insert a column of tags that is normal for cat: A, but reversed for cat:...
<p>EDIT: Because is necessary processing each concsecutive group separately I try create general solution:</p> <pre><code>tag = ['a','b','c'] r = range(len(tag)) r1 = range(len(tag)-1, -1, -1) print (dict(zip(r1, tag))) {2: 'a', 1: 'b', 0: 'c'} m1 = master['cat'].eq('A') m2 = master['cat'].eq('B') s = master['cat']....
pandas
2
98
58,123,825
Input to reshape is a tensor with 'batch_size' values, but the requested shape requires a multiple of 'n_features'
<p>I'm trying to make own attention model and I found example code in here: <a href="https://www.kaggle.com/takuok/bidirectional-lstm-and-attention-lb-0-043" rel="nofollow noreferrer">https://www.kaggle.com/takuok/bidirectional-lstm-and-attention-lb-0-043</a></p> <p>and it works just fine when I run it without modifi...
<p>Your input shape must be <code>(150,1)</code>. </p> <p>LSTM shapes are <code>(batch, steps, features)</code>. It's pointless to use LSTMs with 1 step only. (Unless you are using custom training loops with <code>stateful=True</code>, which is not your case). </p>
python-3.x|numpy|tensorflow|keras
1
99
57,998,473
np.vectorize for TypeError: only size-1 arrays can be converted to Python scalars
<p>I tried to vectortorize as per previous questions but still doesn't work.</p> <pre><code>import numpy as np import math S0 = 50 k_list = np.linspace(S0 * 0.6, S0 * 1.4, 50) K=k_list d1 = np.vectorize(math.log(S0 / K)) print(d1) </code></pre>
<pre><code>In [141]: import math ...: ...: ...: S0 = 50 ...: ...: k_list = np.linspace(S0 * 0.6, S0 * 1.4, 50) ...: ...: K=k_list ...: ...: d1 = np.vectorize(math.log(S0 / K)) ------------------------------------------...
python|python-3.x|numpy
1