Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
7