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
357,400
57,806,853
pandas plotting barplot with secondary y-axis: misaligned on the x-axis
<p>I am trying to plot a barplot with a secondary y-axis using a pandas DataFrame. The returned graph, however, is misaligned on the x-axis, as shown below</p> <p><a href="https://i.stack.imgur.com/Zzob9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zzob9.png" alt="enter image description here"></...
<p><code>df.plot(kind='bar')</code> plots the bars against <code>range(len(df))</code> and label the ticks with <code>df.index</code>. Since your index is <code>1,2,3,4,5</code>, you see that the line plot is shifted.</p> <p>One work around is to plot <code>pie</code> manually:</p> <pre><code>fig,ax = plt.subplots(fi...
python|pandas|matplotlib
3
357,401
57,918,327
How to select columns based on a condition?
<p>I have pandas DataFrame and I wonder how to select columns that contain any of the substrings from a given list <code>targets</code>:</p> <pre><code>targets = ["c1", "c2"] df = c1_targ c2xxx c3abc ... ... ... </code></pre> <p>Expected result:</p> <pre><code>df = c1_targ c2xxx ... .....
<p>You can join each value of string by <code>|</code> for regex <code>OR</code> - <code>'c1|c2'</code> is <code>c1</code> or <code>c2</code> and then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>DataFrame.filter</code></a>:</...
python|pandas
2
357,402
58,130,145
Pandas and datetime coercion. Can't convert whole column to Timestamp
<p>So, I have an issue. Pandas keeps telling me that </p> <blockquote> <p>'datetime.date' is coerced to a datetime. In the future pandas will not coerce, and a TypeError will be raised. To >retain the current behavior, convert the 'datetime.date' to a datetime with >'pd.Timestamp'. I'd like to get rid of this wa...
<p>In pandas python dates are still poor supported, the best is working with datetimes with no times.</p> <hr> <p>If there are python dates you can convert to strings before <code>to_datetime</code>:</p> <pre><code>df['Some_date'] = pd.to_datetime(df['Some_date'].astype(str)) </code></pre> <p>If need remove times f...
python-3.x|pandas|timestamp|python-datetime
1
357,403
58,157,693
How to convert manipulated data from .fits file to pandas DataFrame
<p>I have a .fits file with some data, from which I have made some manipulations and would like to store the new data (not the entire .fits file) as a pd.DataFrame. The data comes from a file called pabdatazcut.fits.</p> <pre><code>#Sorted by descending Paschen Beta flux sortedpab = sorted(pabdatazcut[1].data , key = ...
<p>You get this because of accesses like <code>sortedpab['ID']</code> I guess. According to the doc <code>sorted</code> returns a sorted list. Lists do not accept strings as <code>id</code> to access elements. They can only be accessed by integer positions or slices. That's what the error is trying to tell you.</p> <p...
python|pandas|astropy|fits
1
357,404
57,732,330
Pandas read_csv - Ignore Escape Char in SemiColon Seperated File
<p>I am trying to load a semicolon seperated txt file and there are a few instances where escape chars are in the data. These are typically <strong>&amp;lt ;</strong> (space removed so it isn't covered to &lt;) which adds a semicolon. This obviously messes up my data and since dtypes are important causes read_csv probl...
<p>Give the following example csv file <code>so57732330.csv</code>:</p> <pre><code>col1;col2 1&amp;lt;2;a 3; </code></pre> <p>we read it using <code>StringIO</code> after <a href="https://docs.python.org/3/library/html.html#html.unescape" rel="nofollow noreferrer">unescaping</a> named and numeric html5 character refe...
python|pandas
1
357,405
57,983,799
Why is buff/cache getting larger and larger while loading a large number of numpy arrays using a for loop?
<p>I'm working on a project where I need to load a large number of <code>numpy</code> arrays saved on the disk using a for loop. The system I'm using is Linux. </p> <p>The image below shows the memory usage during the process</p> <p><a href="https://i.stack.imgur.com/IBuPF.jpg" rel="nofollow noreferrer"><img src="htt...
<p>Based on the short code segment shown, you may be converting Numpy ndarray objects into list objects while manipulating them. Try using all Numpy objects and methods. Also try to avoid <strong>for loops</strong> and use <strong>Numpy vectorized operations</strong> instead. 56GB is a huge amount of memory. Yikes! ...
python|numpy|memory
2
357,406
58,102,038
How to increase accuracy of a Feed-forwardNeural Network?
<p>I am having problem in increasing the accuracy of my Feed-Forward Neural network coded in python. I am not sure whether it's a genuine bug or just an incapability of my math functions but I am getting ambiguous outputs (like 0.5) No matter how much I increase the iterations....my code:-</p> <pre><code>from numpy im...
<p>Your <code>Sigmoid_Derivative</code> function is <strong>wrong</strong>, something that has already been pointed out in a <a href="https://stackoverflow.com/questions/57962057/unwanted-nan-output-in-python-neural-network/57963756#57963756">previous question of yours</a>; it should be:</p> <pre><code>def Sigmoid_Der...
python|numpy|machine-learning|neural-network
3
357,407
57,862,963
Problem loading MEDV column in Boston Dataset
<p>Helloz! I am new to pandas usage... I am using the following code to obtain the Boston dataset, but for some reason the least column (medv) is not loading</p> <pre><code>from sklearn.datasets import load_boston boston = load_boston() print(boston.data.shape) print(boston['data']) print(boston['feature_names']) df =...
<p>I'm not familiar with the Boston dataset, but when I load DESCR into pandas, I get a description of the dataset. If you look at the description, it says "Median Value (attribute 14) is usually the target". So I think the attribute value of target is the value of MEDV. Therefore, you can load and paste as follows.</p...
python|pandas|dataframe
1
357,408
57,965,069
How do I make xticks equidistant, despite their value?
<p>I'm trying to graph contaminants measured in a sample over time, and some sample dates are closer together. How do I plot this line with the current datetime values, but make each xtick equidistant?</p> <p>This is what I've got so far, currently the ticks are bunched together when the samples were taken closer toge...
<p>There are a few things you can try. </p> <p>First, ensure that your dataframe series called <code>SAMPLEDATE</code> are datetime objects by running <code>pandas.to_datetime(df_TCE.SAMPLEDATE)</code>. Resolve any parsing errors that arise so that you're truly dealing with a datetime x-axis rather than strings.</p> ...
python|pandas|matplotlib
0
357,409
57,819,575
Extract specific words from string
<p>I have a Dataframe like this: </p> <pre><code>Column_A 1. A lot of text inhere, but I want all words that have a comma in the middle. Like this: hello,world. A string can contain multiple relevant words, like hello,python and we have also many whit spaces in ...
<p>Given the specific format of the expected output, it seems that you could use:</p> <pre><code>from itertools import chain l = chain.from_iterable(df.Column_a.str.findall(r'\w+,\w+').values.tolist()) pd.Dataframe(l, columns=['Column_A']) Column_A 0 hello,world 1 hello,python 2 abstract,all 3 this,sign...
python|regex|string|pandas
3
357,410
57,746,259
Get averages for DateTimeIndex periods, then re-distribute them to the original dataframe column
<p>I have lovely code that makes a list of averages of all entries on a given timeindex period. For example, on a dataframe with ten years of data, it will return the average values for each day of the week. What I want to do is propagate these average values back to the entire dataframe in as few lines as possible.</p...
<p>IIUC, this should work </p> <pre><code>result = time_series.groupby('day of week')['value'].transform('mean') </code></pre>
python|pandas|pandas-groupby|datetimeindex
2
357,411
58,034,200
String Panda series to string variable
<p>Have been looking for the way to get a String variable from a string column in dataframe. In the most basic scenario, I have a String variable called name which is spplitted based on space to get a string list (in the example called names). Then, the list is sent as parameter to the function to process each element ...
<p>You can do it by using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a> in the following way:</p> <pre><code>def avg_sentence_vector(ll, *args, **kwargs): return len(ll) df['avg_vector'] = df.apply(lambda row : avg_sentence_vect...
python|pandas
1
357,412
58,031,796
Delete Prices conditional on Date
<p>I have a dataframe shape 3000 x 120. Each column represents daily stock prices for a ticker. The 2nd row of each column represents the date that stock was sold or expected to be sold. (e.g)</p> <pre><code> AAPL GOOGLE IBM **Sell date. 2017/APRIL/01. 2021/FEB/03. 2015/MAR/3** 201...
<p>I am not sure if I understood your concern, but let me try to help. First of all be sure that your dates are formatted as a datetime.date or datetime.datetime (a.k.a. dt.date or dt.datetime). This is required for comparing it to another date.</p> <p>Run the following code and see if this is something you are lookin...
python|pandas|loops
1
357,413
57,888,688
Inconsistent shape between the condition and the input while using seaborn
<p>I am trying to plot a heatmap with seaborn. Here is the list that I am trying to plot:</p> <pre><code>b = [5, 4, 4, 4, 13, 4, 4, 1, 9, 4, 3, 9, 1, 4, 4, 1, 7, 1, 5, 3, 7, 1, 9, 4, 3, 9, 5, 4, 2, 1, 4, 1, 9, 4, 3, 9, 4, 8, 1, 7, 1, 9, 4, 8, 1, 7, 1, 4, 8, 1, 7, 1, 4, 1, 7, 1, 4, 10, 4, 3, 4, 7, 1, 8, 5, 10, 8, 9, 4,...
<pre><code>import numpy as np import seaborn as sns from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt data = np.asarray(b).reshape(633,1) sns.heatmap(data,cmap=ListedColormap(['green', 'yellow', 'red'])) plt.show() </code></pre> <p>heatmap requires 2D dataset <a href="https://seaborn.pydata....
python|python-3.x|numpy|matplotlib|seaborn
6
357,414
58,124,926
Dataframe column to list of strings (with groupby)
<p>I have a dataframe and I want to get one of its columns as a list of strings, so that from something like:</p> <pre><code>df = pd.DataFrame({'customer':['a','a','a','b','b'], 'location':['1','2','3','4','5']}) </code></pre> <p>I can get a dataframe like:</p> <pre><code>a ['1','2','3'] b ['4','5'] </cod...
<p>Just use</p> <pre><code>df.groupby('customer').location.unique() Out[58]: customer a [1, 2, 3] b [4, 5] Name: location, dtype: object </code></pre> <p>This is <code>string</code> type , just did not show the quote </p> <pre><code>df.groupby('customer').location.unique()[0][0] Out[61]: '1' </code></pre> ...
python-3.x|string|pandas|list
1
357,415
57,759,568
Python: how to merge and divide two dataframes?
<p>I have a dataframe <code>df</code> containing the population <code>p</code> assigned to some buildings <code>b</code></p> <pre><code>df p b 0 150 3 1 345 7 2 177 4 3 267 2 </code></pre> <p>and a dataframe <code>df1</code> that associates some other buildings <code>b1</code> to the buildings in ...
<p>IIUC, you can try with merging both dfs on <code>b</code> then <code>stack()</code> and some cleansing, finally group on <code>p</code> and transform <code>count</code> and divide <code>p</code> with that to get divided values on <code>p</code>:</p> <pre><code>m=(df.merge(df1,on='b',how='left').set_index('p').stack...
python|pandas|merge
1
357,416
58,059,805
Retrieve values of excel as python dictionary
<pre><code>Sr. No Name 1 a 2 b 3 c </code></pre> <p>Imagine this is my excel file.</p> <p>And</p> <p>To get the header:</p> <pre><code>dic = pandas.read_excel(excelfile).columns </code></pre> <p>convert excel file into dict:</p> <pre><code>readers = pandas.read_excel(excelfile).to_dict()...
<p>A <code>.to_dict()</code> will create a dictionary where the keys are the names of the columns, and the values lists that contain the values.</p> <p>Indeed, for the given dataframe, we get:</p> <pre><code>&gt;&gt;&gt; df.to_dict() {'Sr. No': {0: 1, 1: 2, 2: 3}, 'Name': {0: 'a', 1: 'b', 2: 'c'}} </code></pre> <p>You ...
python|django|pandas
4
357,417
57,806,121
How to apply rolling line of best fit to a Pandas Dataframe
<p>I need to apply a line of best fit to every day in a dataframe.</p> <p>What I have so far is:</p> <pre><code>def lobf(y): slope, intercept = stats.linregress(np.arange(len(y)), y)[:2] return((slope * np.arange(len(y))) + intercept) rolling_lobf = df[["A"]].rolling(24, axis = 0).apply(lobf) </code></pre> ...
<p>I got it; thanks to Ben.T's comment.</p> <p>What I've ended up doing is taking the average of the points on the line of best fit fitted to the past 24H:</p> <pre class="lang-py prettyprint-override"><code>def lobf(y): slope, intercept = stats.linregress(np.arange(len(y)), y)[:2] return(((slope * np.arange(...
python|pandas
1
357,418
57,795,591
Deleting decimals from a pandas dataframe
<p>I have numbers such as </p> <pre><code>24.00 2.00 3.00 </code></pre> <p>I want to have </p> <pre><code>24 2 3 </code></pre> <p>I have used .astype(int), round() but I keep getting the former. How do I get this to work?</p>
<p>You need to re-assign <code>dataframe</code> (which is, what I suppose your error is):</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(data={"col": [24.00, 2.00, 3.00]}) &gt;&gt;&gt; df.dtypes col float64 dtype: object &gt;&gt;&gt; df col 0 ...
python|pandas
1
357,419
57,738,842
How to save an operation node's output in a graph trained by Tensorflow?
<p>I have trained a deep learning model by Tensorflow. The model is saved as a saved_model.pb and also there are variables and checkpoints saved during training. The model's task is regression. The output is a single scalar. I use the saved model on some new data to test the model accuracy. Now, I want to use the save...
<p>This is how I did it on a DNN learning transfer.</p> <p><strong>Save Trained Model</strong></p> <pre class="lang-py prettyprint-override"><code>self._saver.save(self._session, self._get_save_path(name)) </code></pre> <p><strong>Restore Model</strong></p> <pre class="lang-py prettyprint-override"><code>## restore...
python|tensorflow
1
357,420
58,108,953
How to fix invalid mount config for type "bind": source path must be a directory in Windows docker Container?
<p>I have a keras model (Windows Spyder IDE) and saved for tensorflow serving, and followed the steps in <a href="https://www.youtube.com/watch?v=CUpUPY5g8NE" rel="nofollow noreferrer">https://www.youtube.com/watch?v=CUpUPY5g8NE</a> for deploy.</p> <p>I am using docker-for-windows and running Windows Container (so no ...
<p>This is a well known <a href="https://github.com/moby/moby/issues/30555" rel="nofollow noreferrer">issue</a> bind mounting files is not possible through windows. Although its possible on linux, there are quite some pitfalls, so mounting a directory is preferred. Also its mentioned that it is a platform limitation on...
docker|tensorflow|tensorflow-serving|docker-for-windows
4
357,421
57,860,972
How to fix SyntaxError when reading sqlite3 database into a pandas DataFrame
<p>I'am trying to read sqlite3 database using pandas. Unfortunately in my code is SyntaxError but i can't find it.</p> <p>The code is the same as in many tutorials so i don't know where is the problem</p> <pre><code>import pandas as pd import sqlite3 con = sqlite3.connect("activity_log.db") query = "SELECT * from lo...
<p>The sqlalchemy package looks like 6 years old (<code>sqlalchemy\sql\expression.py.py", line 2452</code>), before an important refactoring.</p> <p>You should remove this package and reinstall it with a newer version or try an update with:</p> <pre><code>pip install SQLAlchemy --upgrade </code></pre>
python|pandas|sqlite|sqlalchemy
1
357,422
57,895,862
pandas groupby count based on conditions
<p>I am trying to add a column to a dataframe that would give me a count of the type of payment returns that a customer has on their account.</p> <p>This is what the dataframe looks like: </p> <pre><code>CustomerID Return$ Payment Method 000010 10 Credit Card 000010 15 ...
<pre><code>method_dict = df.groupby('CustomerID')['Payment Method'].value_counts().unstack().fillna(0).to_dict() df['CC Return Count'] = df['CustomerID'].map(method_dict['Credit Card']) df['Check Return Count'] = df['CustomerID'].map(method_dict['Check']) </code></pre> <p>Method dict looks like:</p> <pre><code>{'Che...
python|pandas|group-by
0
357,423
58,153,529
how to detect value changed in python, pandas in each object
<blockquote> <p>180762508,1268510763,374723980,293,20180402035748,198,25,1,1 180762508,1268503685,374717256,307,20180402035758,225,38,1,1 180762508,1268492506,374708540,236,20180402035808,222,52,1,1 180762508,1268485868,374697563,248,20180402035818,197,47,1,1 180762508,1268482430,374688520,272,20180402035828,...
<p>If I understood you, you need to get the 5th row, where the change from 0 to 1, in the last column, takes place.</p> <p>I made a dataframe with your first and last column (by the way, you said the 1st column is some kind of unique id, but I see repeated numbers), anyway based on your sample data, one possible solut...
python|pandas
3
357,424
58,122,911
Running elif statements through a table or URLs
<p>I am attempting to see which sharepoint sites are active by pulling the html status code from a table of urls. When I try to apply the elif statement to each row I receive an "Invalid URL 'False': No schema supplied. Perhaps you meant <a href="http://False" rel="nofollow noreferrer">http://False</a>?" message. I'm w...
<p>Try removing <code>url = row in df['2010 Site']</code> and place row instead of url in <code>r= requests.head(url)</code></p>
python-3.x|pandas|python-requests
0
357,425
58,041,146
How can I convert 23 years 0 months into numerical value so that I can use it in Predictive Modelling
<p>I have a dataset in which values are in this form </p> <p>23 years 0 months or 2 years 6 months</p> <p>How can I convert it in numerical data or any other form so that it can be used in predictive modelling , Using pandas</p>
<p>Based on what ALollz said in the comments, you could split the line by spaces and add the months as a percentage of a year</p> <pre><code>a = "23 years 6 months" b = a.split(" ") print(str(float(b[0]) + float(b[2])/12)) </code></pre> <p>Output: <code>23.5</code></p>
excel|pandas|python-2.7|data-science|data-modeling
1
357,426
58,041,204
How do I copy values below the existing value until the next non-blank value?
<p>I tried to search a bit, but it's difficult to describe it in words, so it wasn't easy to find (and in the right language).</p> <p>Given:</p> <pre><code> A B C 1 1 2 3 4 2 5 6 3 7 8 9 0 </code></pre> <p>Wanted result:</p> <pre><code> A B C D 1 1 1 2 1 3 1 4 2 2 5 2 6 3 3 7 3...
<p>Your DataFrame has not <em>NaN</em> in "empty" cells, so I assume that:</p> <ul> <li>the <em>dtype</em> of each column is <em>object</em> (actually <em>string</em>),</li> <li>"empty" cells contain either an <strong>empty string</strong> or a <strong>space</strong>.</li> </ul> <p>In such case, one of possible solut...
python|python-3.x|pandas|numpy
2
357,427
57,970,733
Use each neighbor once in sklearn NearestNeighbor
<p>I am comparing two point clouds of different sizes. I don't want to cutoff the last points in the larger pointcloud pc1. For points in pc1 I would like to find the nearest neighbor in pc2. After using this point in pc1 and pc2 it should <strong>not</strong> be used again for any other comparison. Calculate distances...
<p>You can use the scipy libary to calculate the distance between to points.</p> <pre><code>from scipy.spatial.distance import cdist def closest_node_index(node, nodes): index = cdist([node], nodes).argmin() return index final = [] for arr in pc2: i = closest_node_index(arr, pc1) final.append(pc1[i])...
python|numpy|scikit-learn|nearest-neighbor|point-clouds
2
357,428
57,938,377
Copy data from 1 data-set to another on the basis of Unique ID
<p>I am matching two large data-sets and trying to perform update,remove and create operations on original data-set by comparing it with other data-set. How can I update 2 or 3 column out of 10 of original data-set and keep other column's value same as before?</p> <p>I tried merge but no avail.</p> <p><strong>Origina...
<p>answering your question : "When ID match code update all values in date column without changing any value in name column of original data set"</p> <pre><code>original = pd.DataFrame({'id':['1','2'],'full_name':['John','Paul Elbert'],'date': ['02-23-2006','09-29-2001']}) other = pd.DataFrame({'id':['1','2'],'full_na...
python|pandas
0
357,429
57,794,718
How do I use timeseries index within lambda function
<p>I need to use the index location of a timeseries in a lambda function. The lambda function needs to use the location of the index in the transformation. Similar to the question raised in this question: <a href="https://stackoverflow.com/questions/35481061/can-i-use-index-information-inside-the-map-function/35481114"...
<p>IIUC you can first calculate value in index of timeseries x (1/ length of timeseries) and then add the value in <code>df</code> as</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np dates = pd.date_range(start='2018-10-01', periods=365) df = pd.DataFrame(np.random.randint(...
python|pandas|datetime|time-series
0
357,430
58,083,261
How to change the data type of column of a Dataframe from float to int which has NaN values in it?
<p><strong>This is not a duplicate. All other question, you have to set <code>dtype='Int64'</code> or <code>pd.Int64Dtype()</code> while constructing the <code>DataFrame</code></strong> </p> <p>I have a dataframe with a column name <code>score</code> which has <code>float,Nan</code> values in it. I want to change the ...
<p>You can try this..</p> <pre><code>import numpy as np df['score'].replace('nan', np.nan).fillna(0) </code></pre>
python|pandas|dataframe|series
0
357,431
57,983,481
How to write a listed pandas dataset into an excel xlsx file?
<p>I am trying to create an if statement for my listed dataset to check the conditions in the if statement and if it passes it should add the values from the dataset in the first already created and formated worksheet starting from row[2] and column[0] and if it does not pass it should add the values in the second alre...
<p>The way to edit existing worksheet </p> <pre><code>import csv import pandas as pd with open(r'C:/workbench/SemiFinale/train.csv', 'r') as csvfile: spamreader = csv.reader(csvfile) newlist= list(spamreader) df = pd.DataFrame(newlist[1:], columns=newlist[0]) # Creation of writer object writer= pd.ExcelWrit...
python|pandas|xlsx|xlsxwriter
0
357,432
34,283,234
Concatenate index and string to new column
<p>I have a dataframe of 3 columns(including index):</p> <pre><code> name age 0 satya 24 1 abc 26 2 xyz 29 3 def 32 </code></pre> <p>so need to add one new column <code>detail</code> which will store the detail file name and the value in that column should be like <code>(str(file_index no))</cod...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><code>astype</code></a> with <code>index</code>:</p> <pre><code>df['detail']= 'file_' + df.index.astype(str) print df name age detail 0 satya 24 file_0 1 abc 26 file_1 2 ...
python|string|pandas|dataframe
4
357,433
34,292,076
Pandas Bar plot, how to annotate grouped horizontal bar charts
<p>I ask this question because I haven't found a working example on <strong>how to annotate grouped horizontal Pandas bar charts</strong> yet. I'm aware of the following two:</p> <ul> <li><a href="https://stackoverflow.com/questions/25447700/annotate-bars-with-values-on-pandas-bar-plots">Annotate bars with values on P...
<p>So, I changed a bit the way you construct your data for simplicity:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns sns.set_style(&quot;white&quot;) #for aesthetic purpose only # fake data df = pd.DataFrame({'A': np.random.choice(['foo', 'bar'], 100), ...
python|pandas|plot|bar-chart
3
357,434
34,377,750
What is the `pandas` way to create a column in a dataframe by operating on each row?
<p>I have an <code>apply</code> function that operates on each row in my dataframe. The result of that <code>apply</code> function is a new value. This new value is intended to go in a new column for that row. </p> <p>So, after applying this function to all of the rows in the dataframe, there will be an entirely new...
<p>Two ways primarily:</p> <pre><code>df['new_column'] = df.apply(my_fxn, axis=1) </code></pre> <p>or</p> <pre><code>df = df.assign(new_column=df.apply(my_fxn, axis=1)) </code></pre> <p>If you need to use other arguments, you can pass them to the <code>apply</code> function, but sometimes it's easier (for me) to ju...
python|pandas|dataframe|apply
3
357,435
34,349,316
Synchronous vs asynchronous computation in Tensorflow
<p>In the Tensorflow CIFAR tutorial it talks about using multiple GPUs and gives this warning:</p> <p>"Naively employing asynchronous updates of model parameters leads to sub-optimal training performance because an individual model replica might be trained on a stale copy of the model parameters. Conversely, employing...
<p>Suppose you have n workers.</p> <p>Asynchronous means that each worker just reads parameters, computes updates, and writes updated parameters, without any locking mechanism at all. The workers can overwrite each other's work freely. Suppose worker 1 is slow for some reason. Worker 1 reads parameters at time t, and ...
optimization|machine-learning|tensorflow
9
357,436
34,169,770
TypeError: len() of unsized object when comparing and I cannot make sense of it
<p>I am trying to select sensors by placing a box around their geographic coordinates:</p> <pre><code>In [1]: lat_min, lat_max = lats(data) lon_min, lon_max = lons(data) print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5)) Out[1]: [ 32.87248 33.10181 -94.37297 -94.21224] In [2]: selec...
<p>I'm not familiar with NumPy nor Pandas, but the error is saying that one of the objects in the comparison <code>if len(self) != len(other)</code> does not have a <code>__len__</code> method and therefore has no length.</p> <p>Try doing <code>print(sens_data)</code> to see if you get a similar error.</p>
python-3.x|pandas|python-3.5
3
357,437
34,357,430
Tensorflow: No shape function registered for standard op: ExtractGlimpse. Where do I add my code for the shape function?
<p>I am trying to build a tensorflow graph using <code>tf.image.extract_glimpse</code>. </p> <p>Unfortunately I think there is a bug in the API itself. I am receiving the error <code>No shape function registered for standard op: ExtractGlimpse</code></p> <p>There is actually the following code in <code>/usr/local/lib...
<p>This looks like a bug in TensorFlow: the shape function is defined in the correct place, but the code in <code>attention_ops.py</code> is never executed, so the shape function is never registered.</p> <p>I will fix it upstream, but in the meantime you can fix it by adding the following line to your program:</p> <p...
python|tensorflow
4
357,438
34,325,176
Blockwise operations in Numpy
<p>Are there any convenience utilities for doing blockwise operations on Numpy arrays?</p> <p>I am thinking of operations like Ising spin renormalization where you divide a matrix into blocks and return matrix where each block is replaced by its sum, average or other function.</p>
<p>You might be looking for <a href="https://stackoverflow.com/a/28207538/190597">superbatfish's <code>blockwise_view</code></a>. This uses <code>np.lib.stride_tricks.as_strided</code> to create a view of the array which places "blocks" of the array in their own axes. </p> <p>For example, suppose you have a 2D array s...
arrays|numpy|matrix
7
357,439
34,361,892
Pip wheel is building a new wheel when one is already present
<p>I'm trying to build a wheel for <code>pandas</code> at <code>0.17.1</code>. I want it to use <code>numpy</code> version <code>1.9.2</code>. I have a wheel for that version of <code>numpy</code> already built in <code>$PWD/wheelhouse</code>, and a few other <code>pandas</code> dependencies as well:</p> <pre><code>ls...
<p>That's not how wheel works. pandas requires a <code>&gt;= 1.7.0</code> version of numpy. You're trying to force it to look for 1.9.2 even though there's already a newer version of numpy. Even if you already have it in your wheelhouse dir, it will check PyPI for the latest version of numpy as this is what is stated i...
python|numpy|pandas|pip|python-wheel
0
357,440
33,979,983
insert rows from Pandas dataframe into mongodb collection as individual documents using Python
<p>I have been attempting to insert the rows of a pandas dataframe into a mongodb collection as individual documents. I am pulling the data from MongoDB using pymongo, performing some transformations, running a scoring algorithm, and adding the score as an additional column to the dataframe. The last step will be to i...
<p>You need to convert your DataFrame to list of dictionary using the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.to_dict.html" rel="noreferrer"><code>.to_dict()</code></a> method.</p> <pre><code>&gt;&gt;&gt; from pprint import pprint # to pretty print the cursor result. &gt...
python|mongodb|pandas|dataframe|pymongo
7
357,441
34,093,782
I am not able to import and use numpy in my python shell
<p>I have installed NLTK with Python and the tokenising and tagging part is working fine but I'm unable to work on <code>Numpy</code> as I'm getting the error which says:</p> <blockquote> <p>ImportError: No module named 'numpy'</p> </blockquote> <p><a href="http://i.stack.imgur.com/a5q6V.jpg" rel="nofollow">This im...
<p>Are you sure you are using the correct interpreter (2.x vs. 3.x)? Did you install numpy for 2 or 3 using pip2 or pip3? Typically pip will be assigned to whatever your default interpreter is. Double check with <code>pip --version</code>, also check if numpy is installed with <code>pip list</code>.</p> <p>As an aside...
python|numpy|nltk
1
357,442
34,052,650
Aggregation fails on function that uses an index
<p>Apologies for the simple question, I'm an R user who is relatively new to python. </p> <p>Consider the following minimal example:</p> <pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', ...
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation" rel="nofollow">Aggregation</a> docs -</p> <blockquote> <p>Aggregating functions are ones that reduce the dimension of the returned objects, for example: mean, sum, size, count, std, var, sem, describe, first, last, nth, min, m...
python|pandas
1
357,443
34,024,503
Approximate polygons from image (map)
<p>So I have this map: <a href="https://i.stack.imgur.com/IODrs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IODrs.jpg" alt="original map"></a></p> <p>I've already done some filtering and now I have the following image: <a href="https://i.stack.imgur.com/H7mMb.png" rel="nofollow noreferrer"><img ...
<p>So when I downloaded the image, I got a very disjoint kind of image. So what I did was I dilated it.</p> <pre><code>import numpy as np from skimage import io, measure, morphology img = io.imread('img.png', as_grey=True) img = morphology.binary_dilation(img, selem=np.ones((5,5))) </code></pre> <p>Then what I did w...
python|numpy|image-processing|scipy|scikit-image
0
357,444
34,207,339
How to get all rows with invalid np.datetime64 dates in a pandas DataFrame
<p>I have a pandas DataFrame which has a column, "date_col" with date strings. I would like to filter the DataFrame for all rows where the date strings in this column would throw a <code>ValueError</code> if parsed by <code>numpy.datetime64</code>. I'm looking for something along the lines of:</p> <pre><code>bad_rows ...
<p>just do <code>pd.to_datetime(df['date_col'], errors='coerce')</code> this will produce <code>NaT</code> where the strings are invalid</p> <p>Example:</p> <pre><code>In [307]: df = pd.DataFrame({'date':['2015-02-01', 'sausage', '2011-01-33']}) df Out[307]: date 0 2015-02-01 1 sausage 2 2011-01-33 I...
python|datetime|numpy|pandas
3
357,445
34,262,007
How to use f2py to call a big fortran package
<p>I need to use a math package which is entirely written in Fortran. The package is not in a single file but is compiled into an archive file (.a file). </p> <p>I have the full source code. I don't know Fortran.</p> <p>I did a quick read on f2py document here: </p> <p><a href="http://docs.scipy.org/doc/numpy-dev/f2...
<p>Since you say you only need to call 3-5 different functions, one easy way is to use <code>ctypes</code>. It's included with Python, and while at first glance it appears to be made for calling C functions, on many systems Fortran is compatible with C for the most part.</p> <p>See here: <a href="https://docs.python....
python|numpy|fortran|f2py
0
357,446
34,373,311
Fastest way to get average value of frequencies within range
<p>I am new in python as well as in signal processing. I am trying to calculate <code>mean</code> value among some frequency range of a signal. </p> <p>What I am trying to do is as follows:</p> <pre><code>import numpy as np data = &lt;my 1d signal&gt; lF = &lt;lower frequency&gt; uF = &lt;upper frequency&gt; ps = np....
<p>If you really have a signal of 15 GB size, you'll not be able to calculate the FFT in an acceptable time. You can avoid using the FFT, if it is acceptable for you to approximate your frequency range by a band pass filter. The justification is the <a href="https://en.wikipedia.org/wiki/Poisson_summation_formula" rel=...
python|performance|numpy|signal-processing
7
357,447
34,184,841
Python Pandas - Read csv file containing multiple tables
<p>I have a single <code>.csv</code> file containing multiple tables.</p> <p>Using Pandas, what would be the best strategy to get two DataFrame <code>inventory</code> and <code>HPBladeSystemRack</code> from this one file ?</p> <p>The input <code>.csv</code> looks like this:</p> <pre><code>Inventory System Nam...
<p>If you know the table names beforehand, then something like this:</p> <pre><code>df = pd.read_csv("jahmyst2.csv", header=None, names=range(3)) table_names = ["Inventory", "HP BladeSystem Rack", "Network Interface"] groups = df[0].isin(table_names).cumsum() tables = {g.iloc[0,0]: g.iloc[1:] for k,g in df.groupby(gro...
python|excel|python-2.7|csv|pandas
19
357,448
36,998,069
Breaking out column by groups in Pandas
<p>If I have a DataFrame like this:</p> <pre><code> type value group a 10 one b 45 one a 224 two b 119 two a 33 three b 44 three </code></pre> <p>how do I make it into this:</p> <pre><code> type one two three a 10 224 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0...
python|pandas
2
357,449
36,723,702
how to optimize the following code?
<p>I'm writing a program in python to replace some values of a data frame, the idea is that I have a file called file.txt and looks like this:</p> <pre><code>A:s:Y:0.1:0.1:0.1:0.2:0.1 B:r:D:0.3:0.5:0.1:0.2:0.2 C:f:C:0.3:0.4:0.2:-0.1:0.4 D:f:C:0.1:0.2:0.1:0.1:0.1 F:f:C:0.1:-0.1:-0.1:0.1:0.1 G:f:C:0.0:-0.1:0.1:0.3:0.4 H...
<p>You can use <code>where</code> instead:</p> <pre><code>for k, v in lookup.items(): df = df.where(~df.isin(v), k) </code></pre> <p>This says to retain the values of <code>df</code> when those values are not contained in <code>v</code>. Otherwise, replace them with the value <code>k</code>. The assignment overwr...
python|pandas
4
357,450
36,852,180
Pivot groups of row data into columns using Pandas
<p>I've got data I'm reading in as a dataframe from a CSV using Pandas (in Python). The CSV looks basically like the following:</p> <pre><code>image img1.jpg date Thursday, May 5 link bit.ly/asdf subject 'Unique subject line 1' image img2.jpg date Tuesday, May 17 link bit.ly/zxcv subject 'Uniqu...
<p>The issue is that, as the data currently is formatted, there isn't a unique way to group the images during a pivot. Any date could be grouped with <code>img1.jpg</code> during a pivot, as there isn't any additional data saying which date should correspond to each image.</p> <p>To fix this, we just need to add an a...
python|csv|pandas
1
357,451
36,977,425
update cell value of duplicates without using for loop
<p>How can I get same results as the following code without using for loop: my typical data has ~500k rows, and as it is, the code is too time consuming.</p> <pre><code>data={'key1':[1,2,1,1,2,3,2,2],'key2':[2,2,2,2,2,4,2,2],'class':[5,10,'NaN','NaN','NaN',6,'NaN','NaN']} frame = pd.DataFrame(data,columns=['key1','key...
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> by columns <code>key1</code> and <code>key2</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow...
pandas|duplicates
2
357,452
36,946,677
Pandas DataFrame column from a tuple
<p>I have a dictionary:</p> <pre><code>employer = {'CrntEmp_city': ('XXX', 'XXX'), 'CrntEmp_cntry': ('XXX', 'XXX'), 'CrntEmp_orgNm': ('XXXX LLC', 'YYYY LLC'), 'CrntEmp_orgPK': ('1234567891', '1234567899'), 'CrntEmp_postlCd': ('12345', '12345'), 'CrntEmp_state': ('AK', 'AK'), 'CrntEmp_str1': ('999 XXX', '999 XXX'), '...
<p>You basically want something like: <code>pd.DataFrame({'col1': [(a, b)], 'col2': [(c, d)]})</code></p> <p>You can achieve that using a dictionary comprehension as follows in Python 2. For Python 3, use <code>employer.iter()</code> instead.</p> <pre><code>&gt;&gt;&gt; pd.DataFrame({k: [tuple(v)] for k, v in employ...
python|dictionary|pandas|tuples
2
357,453
36,944,884
Calculating percentile for specific groups
<p>I have 3 columns. <code>Product Id</code>, <code>Price</code>, <code>Group</code> (values A, B, C, D)</p> <p>I want to get price percentile for each group and I am running the following code.</p> <pre><code>for group, price in df.groupby(['group']): df['percentile'] = np.percentile(df['price'],60) </code></pre...
<p>I think you can use in loop not all <code>DataFrame</code> <code>df</code> with column <code>price</code>, but group <code>price</code> with column <code>price</code>:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(1) df = pd.DataFrame(np.random.randint(10, size=(5,3))) df.columns = ['Product...
python|loops|numpy|pandas|group-by
7
357,454
36,877,811
Sort values within dataframe grouped by multiple columns
<p>I have a dataframe that is in this form.</p> <pre><code> Type Major GPA F A 2.6 T B 3.4 T C 2.9 F A 1.8 T B 2.8 F C 3.5 ... </code></pre> <p>I'd like to group the Dataframe ("students") by <code>Type</code> and <code>Major</co...
<pre><code>most_popular = students.groupby(['Type', 'Major']).size().reset_index().sort_values(['Type', 'Major'], ascending=[True, False])[:20] </code></pre> <p>The key is to sort in both ASC and DSC order, you can use:</p> <pre><code>.sort_values(['Type', 'Major'], ascending=[True, False]) </code></pre>
python|sorting|pandas|group-by
1
357,455
37,017,523
Python: Best way to place data in a list and as time progresses update and delete oldest value
<p>essentially I have a stream of data coming in from this code that updates every minute with the newest prices:</p> <pre><code>prices = data.history(context.stocks, "close", 15600, "1m") </code></pre> <p>I'm looking to get this historical data put into some sort of list when every minute this code feeds the newest ...
<p>You may consider using <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>deque</code></a> with option <code>maxlen</code>.</p> <blockquote> <p>If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the s...
arrays|list|sorting|pandas|quantitative-finance
1
357,456
36,952,573
Different result with vectorized code to standard loop in numpy
<p>I have the following two functions:</p> <pre><code>def loop(x): a = np.zeros(10) for i1 in range(10): for i2 in range(10): a[i1] += np.sin(x[i2] - x[i1]) return a </code></pre> <p>and</p> <pre><code>def vectorized(x): b = np.zeros(10) for i1 in range(10): b += n...
<p>It's because you don't make the operation in the same order.</p> <p>For the equivalent totally vectored solution, do <code>c=sin(add.outer(x,-x))).sum(axis=0)</code>.</p> <pre><code>In [8]: (c==loop(x)).all() Out[8]: True </code></pre> <p>And you win the full avantage of vectorisation :</p> <pre><code>In [9]: %t...
python|python-2.7|numpy
5
357,457
36,808,725
Creating a highly customizable RNN in Tensorflow
<p>I am trying to implement an RNN without using the RNN functions provided by tensorflow. Here is the code I tried that eventually gave me an error</p> <pre><code>import tensorflow as tf tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=(5,5)) InitialState = tf.zeros((5,1)) h = InitialState W1 = tf.Variabl...
<pre><code>import tensorflow as tf import numpy as np hidden_size = 2 # hidden layer of two neurons input_size = 5 # Weight of x will the be (hidden_layer_size x input_size) Wx = tf.Variable(tf.random_normal([hidden_size, input_size], stddev=0.35), name="Wx") # Weight of y will be (input_...
tensorflow|recurrent-neural-network
1
357,458
36,695,997
Histogram plotting one column (string) with second column (int) in pandas
<p>I've got a dataset with several columns where I want to create a histogram outputting a string column to the x-axis and an int value to the y-axis.</p> <p>Sample data:</p> <pre><code>100039241 lustalloverme 275 598 16123 0 28 Dec 2009 20:26:38 GMT diamond lane ; * 100039367 A7madista 213 420 13849 ...
<p>if 'User Location' is unique, you may want bar plot</p> <pre><code>df.plot( x='User Location', y='Follower Count', kind='bar') </code></pre> <p>if one location has multi follower count, i.e. loc1, 10 loc1, 12 loc2, 20 loc2, 30</p> <p>you can aggregate the data frame first</p> <pre><code>df.groupby('User_location...
python|pandas|plot|graph
0
357,459
36,773,947
Theano/numpy advanced indexing
<p>I have a 4d theano tensor (with the shape (1, 700, 16, 95000) for example) and a 4d 'mask' tensor with the shape (1, 700, 16, 1024) such that every element in the mask is an index that I need from the original tensor. How can I use my mask to index my tensor? Things like sample[mask] or sample[:, :, :, mask] don't r...
<p>So in the lack of an answer, I've decided to use the more computationally intensive solution which is unfolding both my data the the indices tensors, adding an offset to the indices to bring them to global positions, indexing the data and reshaping it back to original.</p> <p>I'm adding here my test code, including...
python|numpy|machine-learning|computer-vision|theano
0
357,460
37,065,071
Python: Load CSV, first column as row names, first row as column names
<p>I want to load a CSV file using Python2.7, in which the first row contains column names and the first column contains row names. </p> <p>My CSV file looks like beneath. </p> <pre><code> A B C D a 1. 2. 3. 4. b 5. 6. 7. 8. </code></pre> <p>I don't know how to do that with numpy or pandas. Can someone enlight...
<p>You could use <a href="https://www.google.ru/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;ved=0ahUKEwjjlPWg4MTMAhXBjywKHZpNCB0QFggdMAA&amp;url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Fgenerated%2Fpandas.read_csv.html&amp;usg=AFQjCNE1cTwGgwS3WFrM8PRoP9YzTbLAGA&amp;sig2=Cj_KPxrM65-Ve...
python|python-2.7|csv|numpy|pandas
3
357,461
36,987,317
Python: Groupby hour include null values
<p>Using citibike data: <a href="https://s3.amazonaws.com/tripdata/index.html" rel="nofollow">https://s3.amazonaws.com/tripdata/index.html</a></p> <pre><code>tripduration starttime stoptime start_station_id start_station_name start_station_latitude start_station_longitude end_station_id end_station_name ...
<p>As mentioned in the comments, the solution is as such:</p> <p>1) Create a DataFrame with a full range of hours, all set to <code>bikes_parked=0</code></p> <p>2) Update this DF with the relevant data from the grouped table by using:</p> <pre><code>df.loc[bikes_parked.index, 'bikes_parked'] = bikes_parked.bikes_par...
python|pandas|group-by
0
357,462
36,981,914
Find indexes of equal numpy 2D rows
<p>I have a Python list of 2D numpy arrays (all with the same shape) and I want to extract the indexes of equal arrays. I came up with this:</p> <pre><code>a = np.array([[1, 2], [3, 4]]) b = np.array([[1, 2], [3, 4]]) c = np.array([[3, 4], [1, 2]]) d = np.array([[3, 4], [1, 2]]) e = np.array([[3, 4], [1, 2]]) f = np.a...
<p>Given the fact that the input arrays in the list are of identical shapes, you can concatenate the list of arrays into a single 2D array, with each row representing each element of the input list. This makes the further computations easier and facilitates vectorized operations. The implementation would look something...
python-3.x|numpy
1
357,463
54,835,840
How can I set the value for a specific row for a Pandas DataFrame in a for loop?
<pre><code>for petid in X['PetID']: sentiment_file = datapath + '/train_sentiment/' + petid + '.json' if os.path.isfile(sentiment_file): json_data = json.loads(open(sentiment_file).read()) X['DescriptionLanguage'] = json_data['language'] X['DescriptionMagnitude'] = json_data['documentSen...
<p>You can use .loc to set a individual value instead of a whole column. Here is a contained example</p> <pre><code>import pandas as pd import numpy as np X = pd.DataFrame(np.arange(5), columns=['PetID']) for ind, row in X.iterrows(): petid = row['PetID'] X.loc[ind, 'DescriptionLanguage'] = 'No description f...
python|pandas
2
357,464
55,072,643
Remove all columns that are of a certain value in a specific row
<p>I'm looking for a way to remove all columns from my pandas df based on the value of a single row, e.g., return a new df with all rows but only those columns that are zero in row X. </p>
<p>You can do this with <code>loc</code> and <code>iloc</code></p> <pre><code>df = pd.DataFrame({'a':[1, 20, 30, 4, 0], 'b':[1, 0, 3, 4, 0], 'c':[1, 3, 7, 7, 5], 'd':[1, 8, 3, 8, 5], 'e':[1, 11, 3, 4, 0]}) df.loc[:, df.iloc[4,:] == 0] a b e 0 1 1 1 1 ...
python|python-3.x|pandas
1
357,465
55,058,506
pandas map to dictionary of array
<p>i have a df of country codes:</p> <pre><code> cntr 0 CN 1 CH </code></pre> <p>and I want to map the full name and region I have from a dictionary</p> <pre><code>cntrmap = {"CN":["China","Asia"],"CH":["Switzerland","Europe"]} </code></pre> <p>I was hoping in something like this, but doesn't work..</p> <pre><cod...
<p>You can create helper DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer"><code>DataFrame.from_dict</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow norefe...
python|pandas|dataframe|mapping
1
357,466
54,937,929
Pandas check multiple rows and copy a different row
<p>I've this following scenario.</p> <p>Table 1</p> <pre><code>column_a column_b 1 10 2 20 3 30 4 40 </code></pre> <p>Table 2</p> <pre><code>column_a new_column 1 10 2 20 3 30 5 0 </code></pre> <p>If <strong>values in column_a in both tables match</...
<h2><code>map</code> + <code>fillna</code></h2> <pre><code>df2['new_col'] = df2.column_a.map(df1.set_index('column_a').column_b).fillna(0) print(df2) column_a new_col 0 1 10.0 1 2 20.0 2 3 30.0 3 5 0.0 </code></pre>
python|pandas|numpy|dataframe
3
357,467
55,076,547
OHLC Sampling is creating wrong timestamps candles
<p>The data needed for sampling is coming from SQLite. It has been made available here: <a href="https://pastebin.com/LU7YApkX" rel="nofollow noreferrer">https://pastebin.com/LU7YApkX</a></p> <p><strong>Code:</strong></p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connect('sqlite_database.db') quer...
<p>When you resample e.g. by <code>10min</code> it creates 10-min intervals, and <code>2019-01-24 09:10:00</code> corresponds to <code>2019-01-24 09:10:00 - 2019-01-24 09:19:59</code>:</p> <pre><code>df['ltp'].resample('10min').ohlc().bfill() </code></pre> <p>Output:</p> <pre><code> open hig...
python|pandas
1
357,468
54,709,130
Pandas ewm doesn't match marketwatch
<p>I'm getting a 5 minute feed and storing it in the dataframe. My EWM 200 doesn't match Marketwatch EWM 200</p> <p>I've tried the piece of code posted on Feb 13th 2018. My data has dates already sorted in ascending order and for some reason, it doesn't do the trick</p> <pre><code> df = df.drop(df.index[-1]) p...
<p>If that is all the data you have, you are calculating ewm 200 on 30 samples, so for sure you won't have the same results.</p>
python|pandas
1
357,469
54,720,996
How to Remove Rows from DataFrame Based on Values in Series
<p>I know it's an easy question, but I just can't find a way to solve it.</p> <p>I have a <code>DataFrame</code> that I want to remove rows based on values in another <code>series</code>.</p> <pre><code>X 1 2 5 6 7 10 12 13 0 5 4 4 4 0 4 0 3 1 3 0 3 0 0 0 0 3 2 4 0 ...
<p>First filter index values by <code>Series</code> and then remove rows by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a>:</p> <pre><code>b = Vtk.index[Vtk == 3] print (b) Int64Index([2, 4], dtype='int64') newX = X....
python|python-3.x|pandas|dataframe|jupyter-notebook
4
357,470
54,953,883
Keras autoencoder with Tensorflow Dataset API and logging to Tensorboard
<p>I have simple autoencoder in Keras, I want to use logging to tensorboard (thus I need passing validation data), and load the data from TFRecord using the Tensorflow Dataset API using prefetch. I read some articles about it, but they either omitted validation pipeline, or the fact that passing the data directly with...
<p>Few options:</p> <ol> <li>Have you looked at this link <a href="https://github.com/keras-team/keras/issues/3358" rel="nofollow noreferrer">https://github.com/keras-team/keras/issues/3358</a> (solution by juiceboxjoe)?<br> Write a TensorboardWrapper which loads the validation data from the generator and pass that as...
python|tensorflow|keras|tensorflow-datasets
0
357,471
54,962,682
Count how many values fall in each bin
<p>Suppose that I have a set partitions <code>P</code> over the interval <code>[0,1)</code>. <code>P</code> has the length <code>N</code>. For example:</p> <pre><code>P = np.array([0,0.05,0.1,0.3,0.7,1]) </code></pre> <p>which divides <code>[0,1)</code> to the following intervals: </p> <pre><code>[0,0.05), [0.05,0.1...
<p>One way is using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer"><code>np.searchsorted</code></a> to obtain the indices where the elements in <code>U</code> should be inserted in <code>P</code> to maintain order, followed by <a href="https://docs.scipy...
python|arrays|numpy|partition
2
357,472
54,916,991
Python plotting time list
<p>Sorry for my bad English.</p> <p>I have a list : </p> <pre><code>found_time = ['2019-02-28 00:24:16', '2019-02-28 00:22:30', '2019-02-27 08:08:21', ... ... , '2019-02-01 22:21:10', '2019-02-01 00:21:10'] </code></pre> <p><a href="https://i.stack.imgur.com/ToSok.jpg" rel="nofollow noreferrer"><img src="https://i....
<pre><code>s = pd.Series(np.ones(len(found_time)), index=pd.DatetimeIndex(found_time)) plt.scatter(s.index.time, s.index.date, color='k') # yticks yticks = pd.date_range('2019-02-01', '2019-02-28', freq='D') plt.yticks(yticks, [y.strftime('%m-%d') for y in yticks]) plt.ylim('2019-02-01', '2019-02-28') # xticks xtic...
python|python-3.x|pandas|matplotlib|plot
1
357,473
54,914,106
Fastai learner not loading
<p>So I'm trying to load a model using:</p> <pre><code>learn = create_cnn(data, models.resnet50, lin_ftrs=[2048], metrics=accuracy) learn.clip_grad(); learn.load(f'{name}-stage-2.1') </code></pre> <p>But I get the following error</p> <pre><code>RuntimeError: Error(s) in loading state_dict for Sequential: size misma...
<p>Use <a href="https://docs.fast.ai/vision.learner.html#cnn_learner" rel="nofollow noreferrer"><code>cnn_learner</code></a> method and latest <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer"><code>Pytorch</code></a> with latest <a href="https://docs.fast.ai/install.html" rel="nofollow noref...
machine-learning|model|pytorch|resnet|fast-ai
4
357,474
54,940,487
how to find percentage of total in groupby in pandas
<p>I have following dataframe in pandas</p> <pre><code> Date tank hose quantity count set flow 01-01-2018 1 1 20 100 211 12.32 01-01-2018 1 2 20 200 111 22.32 01-01-2018 1 3 20 200 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>GroupBy.transform</code></a> with lambda function, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add_prefix.html" rel="noreferrer"><code>add_prefix</...
python|pandas
6
357,475
55,126,493
Implementing fast dense feature extraction in PyTorch
<p>I am trying to implement this paper in PyTorch <a href="https://www.dfki.de/fileadmin/user_upload/import/9245_FastCNNFeature_BMVC.pdf" rel="nofollow noreferrer">Fast Dense Feature Extractor</a> but I am having trouble converting the Torch implementation example they provide into PyTorch. </p> <p>My attempt thus far...
<p>It is your lucky day as I have recently uploaded a PyTorch and TF implementation of the paper <a href="https://arxiv.org/abs/1805.03096" rel="nofollow noreferrer">Fast Dense Feature Extraction with CNNs with Pooling Layers</a>.</p> <p>An approach to compute patch-based local feature descriptors efficiently in prese...
python|pytorch
1
357,476
54,937,532
'NoneType' object has no attribute 'add_summary'
<p>I'm having trouble with visualizing the weights and bias of my model using tensorboardX. Here is my model (it's pretty simple anyway):</p> <pre><code> self.pipe = nn.Sequential(nn.Linear(9, 128), nn.ReLU(), nn.Linear(128, 256), ...
<p>The posted code snippet is insufficient to root cause the issue.</p> <p>The member variable file_writer is set to None when the close() method is invoked on writer. Please check if the close() method was invoked on writer. The close() method is also invoked when the writer object is used as a Context manager and th...
machine-learning|error-handling|parameters|pytorch|tensorboardx
1
357,477
54,876,346
Pybind11 and std::vector -- How to free data using capsules?
<p>I have a C++ function that returns a <code>std::vector</code> and, using Pybind11, I would like to return the contents of that vector as a Numpy array without having to copy the underlying data of the vector into a raw data array.</p> <p><strong>Current Attempt</strong></p> <p>In <a href="https://stackoverflow.com...
<blockquote> <p><em>After an offline discussion with a colleague I resolved my problem. I do not want to commit an SO faux pas so I won't accept my own answer. However, for the sake of using SO as a catalog of information I want to provide the answer here for others.</em></p> </blockquote> <p>The problem was simple:...
python|c++|numpy|c++11|pybind11
10
357,478
54,718,027
PyTorch: What does @weak_script_method decorator do?
<p>In the <a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear" rel="nofollow noreferrer"><code>torch.nn.Linear</code></a> class (and other classes too), the <code>forward</code> method includes a <code>@weak_script_method</code> decorator as follows: </p> <pre><code>@weak_script_metho...
<p>You can find the exact <a href="https://github.com/pytorch/pytorch/blob/3a39ce0f419ef8dd88c10ed72aef83c9d5f22c7f/torch/_jit_internal.py" rel="nofollow noreferrer">decorator location</a> to get the idea.</p> <pre><code>def weak_script_method(fn): weak_script_methods[fn] = { "rcb": createResolutionCallbac...
python|decorator|pytorch
1
357,479
54,886,690
Python- replace negative numbers shown as a string with parentheses into a float
<p>I have a data set with where some of the negative numbers are shown in the format (3.4) and some as -3.4. I am trying to adjust all the parentheses to be float format.</p> <p>The below formula gives me an error</p> <blockquote> <p>replace() argument 1 must be str, not list</p> </blockquote> <pre><code>Total['Ra...
<p>Looks like you need.</p> <p><strong>Demo:</strong></p> <pre><code>import pandas as pd df = pd.DataFrame({"Rate": ["(.35)", "1.2", "-2"]}) print(df["Rate"].str.replace("(", "-").str.rstrip(")").astype(float)) </code></pre> <p><strong>Output:</strong></p> <pre><code>0 -0.35 1 1.20 2 -2.00 Name: Rate, dtype...
python|pandas|dataframe
1
357,480
55,058,943
Data generated with Tensorflow Dataset.from_generator results in error when iterator.get_next() is called on it
<p>I'm new to Tensorflow. I followed some online posts and wrote code to get data from a generator. The code looks like this:</p> <pre><code>def gen(my_list_of_files): for fl in my_list_of_files: with open(fl) as f: for line in f.readlines(): json_line = json.loads(line) ...
<pre><code>{ "features": ["1","2"], "labels": "2" } </code></pre> <p>I don't see your error when I execute this code.</p> <pre><code>def gen(): with open('jsondataset') as f: data = json.load(f) features = data['features'] labels = data['labels'] print( features) yie...
tensorflow|generator|tensorflow-datasets
0
357,481
54,978,658
Tensorflow python. ValueError: Non-scalar tensor cannot be converted to boolean
<p>I have been trying out these codes related to tensorflow 1.12.2 install together with visual studio 15.9.6. The python version is 3.6.6.</p> <p>The problem lies in the conditional statement in the log_huber function. Any advise on how to solve this is greatly appreciated. The code is appended below:</p> <pre><code...
<p>If you use <a href="https://www.tensorflow.org/api_docs/python/tf/squeeze" rel="nofollow noreferrer">tf.squeeze</a> like this your dimensions are removed.</p> <pre><code>def log_huber(x, m): print (tf.abs(x)) if tf.squeeze(tf.abs(x)) &lt;= tf.squeeze(tf.abs(m)): return x**2 else: return m**2 * (1 - 2 ...
python-3.x|tensorflow|tensorflow-datasets
2
357,482
54,977,442
Pandas how to get top n group by flag column
<p>I have dataframe like below.</p> <pre><code>df = pd.DataFrame({'group':[1,2,1,3,3,1,4,4,1,4], 'match': [1,1,1,1,1,1,1,1,1,1]}) group match 0 1 1 1 2 1 2 1 1 3 3 1 4 3 1 5 1 1 6 4 1 7 4 1 8 1 1 9 4 1 </code></pre...
<p>I believe you need if need top3 groups per column <code>match</code> - use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><code>SeriesGroupBy.value_counts</code></a> with <a href="http://pandas.pydata.org/pandas-docs/s...
python-3.x|pandas
2
357,483
54,911,779
merge from one dataframe values with one dataframe columns
<p>I have one difficulty here. My goal is to create a list of sales for one shop with one dataframe that lists prices by product and one other that lists all the sales in terms of products and quantities (for one period of time)</p> <p>DataFrame 1 : prices</p> <pre><code>prices = pd.DataFrame({'qty_from' : ('0','10',...
<p>If I understand correctly, you can modify the dataframe prices to be able to use the parameter <code>by</code> in <code>merge_asof</code>, using <code>stack</code>:</p> <pre><code>#modify price prices_stack = (prices.set_index(['qty_from','qty_to']).stack() # then products become as a column .r...
python|pandas|merge
0
357,484
55,067,317
Pandas Group by Values and Merge Rows
<p>I have a DataFrame and I want to merge the rows that contain same values</p> <pre><code>toy = [ [10, 11], [21, 22], [11, 15], [22, 23], [15, 33] ] toy = pd.DataFrame(toy, columns = ['ID1', 'ID2']) </code></pre> <pre><code> ID1 ID2 0 10 11 1 21 22 2 11 15 3 22 23 4 15 33 </cod...
<p>Sounds like a network problems so I using <code>networkx</code> </p> <pre><code>import networkx as nx G=nx.from_pandas_edgelist(toy, 'ID1', 'ID2') l=list(nx.connected_components(G)) newdf=pd.DataFrame(l) newdf Out[896]: 0 1 2 3 0 33 10 11 15.0 1 21 22 23 NaN </code></pre>
python|pandas
2
357,485
54,910,290
speed up iterating over pandas while cleaning data
<p>I have got a df of over 1,5 mln rows DataFrame to clean data with regular expressions. That is really slow.. How can I speed things up?</p> <ul> <li>It appears that I have only around 2000 unique rows in this house df, but how do I iterate over the unique values only and then apply the result back to the df? maybe ...
<p>I have managed to speed things up with applying the for loop to the unique values only and then using <code>map</code> function.</p> <pre><code>new_value_dict = {} for i in df['column'].unique(): #some data manipulations new_value = .... new_value_dict.update ({i:new_value}) df['column']=df['column'].m...
python|pandas
0
357,486
54,762,427
How to dynamically add columns with same name on a pandas DataFrame?
<p>I have a list of emails, phones and user info that I want to output in csv but I need to follow a format that contains duplicate columns.</p> <pre><code>email, email, phone, phone, phone, name, address jo@doe.com, re@ko.com, 90192, 2980, 9203, John Doe, 82 High Street re@doe.com, az@ko.com, 1341, 55, 665, Roe Jan, ...
<p>You could get it done using <code>csv</code>:</p> <p>list.txt:</p> <pre><code>email, email, phone, phone, phone, name, address jo@doe.com, re@ko.com, 90192, 2980, 9203, John Doe, 82 High Street re@doe.com, az@ko.com, 1341, 55, 665, Roe Jan, 11 Low Street red@doe.com,,, 55, 111, Roe Jan, 11 Low Street </code></pre>...
python|pandas|data-science
1
357,487
55,047,101
slicing multi d array ,problem with index
<p>i am runnig this line </p> <pre><code> event_probs=np.asarray( self.all_results_probabilities_smoothed[start_frame_num:end_frame_number])[:,0] </code></pre> <p>and this is the print , of this line</p> <pre><code>ndarray:...
<p>You can slice it using numpy's way of indexing/slicing multidimensional arrays</p> <pre><code>&gt;&gt;&gt; a=np.array([[3,2,1],[4,5,6],[9,8,7],[10,11,12]]) &gt;&gt;&gt; a array([[ 3, 2, 1], [ 4, 5, 6], [ 9, 8, 7], [10, 11, 12]]) &gt;&gt;&gt; a[:,0] array([ 3, 4, 9, 10]) </code></pre> <...
python|numpy
0
357,488
54,752,546
Pass a Numpy Array Image to ImageField()
<p>So i got here is a code that detect if the face in the image is in my encodings. So my problem is what if the face is not in the Encodings can i pass a string variable to a OneToOneField() or can i set a default value to it? and also how can i link the image it is in a Numpy Array format yeah i already think about j...
<p>To save a NumPy array in ImageField, I used Django's <a href="https://docs.djangoproject.com/en/3.0/ref/files/file/#the-contentfile-class" rel="nofollow noreferrer">ContentFile</a> class.</p> <pre><code>import cv2 from django.core.files.base import ContentFile def some_function(array): frame_jpg = cv2.imencode...
django|python-3.x|numpy
0
357,489
54,799,719
Python- Convert Dict hidden in List to DataFrame
<p>I'm having trouble using the normalize in JSON for a dictionary that is being recognized as a list. The goal is to create a data frame from yahoo_finance.</p> <pre><code>from yahoofinancials import YahooFinancials import pandas as pd from pandas.io.json import json_normalize ticker = 'AAPL' yahoo_financials = Yaho...
<p>You can use ChainMap from collections.</p> <pre><code>from collections import ChainMap df = pd.DataFrame.from_dict(ChainMap(*user_dict), orient='index') </code></pre> <p>If you don't want to use ChainMap, you can iterate through the dicts in user_dict (a list), and then append these DFs to the main df.</p> <p...
python|json|pandas|list|dictionary
3
357,490
54,816,173
How to accurately round half up with tensorflow
<p>I'm trying to replicate some C++ based code into Python API of Tensorflow, but I'm having few floating point inaccuracy issues, although I have been able to find one of them.</p> <p>Generally, Tensorflow seems to round decimals in a <a href="https://en.wikipedia.org/wiki/Rounding#Round_half_down" rel="nofollow nore...
<p>called bankers rounding nothing wrong about that same thing happening in c# too. you can try something like that:</p> <pre><code>def classical_round(x): return tf.math.floor(x+0.5) sess.run(classical_round(2.5)) #3.0 </code></pre> <p>more information here: <a href="https://en.wikipedia.org/wiki/Rounding#Round...
python|c++|tensorflow|floating-point|rounding
3
357,491
54,827,092
Efficient way to check that dataframe's has a complete grid of data
<p>I want to check whether all data within a dataframe from the top left hand corner of the dataframe to the bottom most right element is complete (the data should be filled in as a rectangle). If is has blank columns or rows after the main body of data this is fine (and it will have this).</p> <p>Example of good and ...
<p>Using <code>numpy</code>:</p> <pre><code>import numpy as np def check_rectangle(df): non_zeros = np.nonzero(df.values) arr = np.zeros(np.max(non_zeros, 1)+1) np.add.at(arr, non_zeros, 1) return np.alltrue(arr) check_rectangle(good_dataframe) # True check_rectangle(bad_dataframe) # False </code></p...
python|pandas|dataframe
0
357,492
49,465,549
Why does defining tf.Session with and without context manager in Tensorflow result in different behaviour?
<p>I noticed that there is a difference when you define session with and without context manager. Here there is an example:</p> <p><strong>With context manager:</strong></p> <pre><code>import tensorflow as tf graph = tf.Graph() with graph.as_default(): x = tf.Variable(0) tf.summary.scalar("x", x) with tf.Se...
<p>You can find the implementation of <code>tf.summary.merge_all()</code> <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/summary/summary.py#L318" rel="noreferrer">here</a>. It works by calling <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops....
python|tensorflow
7
357,493
49,414,902
tensorflow.python.framework.errors_impl.InvalidArgumentError
<p>On the terminal window, it runs fine when an image is passed to tensorflow for image object recognition using:</p> <p><code>python run.py http://image_url.jpg</code></p> <p>However, with JSON data that contains stream of imageURL, it failed with the following main error:</p> <pre><code>InvalidArgumentError: Inval...
<p>I created a <a href="https://github.com/tensorflow/tensorflow/issues/17979" rel="nofollow noreferrer">workaround</a> for the issue. </p>
python|tensorflow|image-recognition
1
357,494
49,553,618
Find and replace in pandas?
<p>I am performing the min-max-scaler operation on a data frame which contains numeric columns, but if the within those numeric columns if any cell contains a string or null value then I am getting an exception. To avoid that I think of converting the string or null cell to 0. How to perform that? my function:</p> <pr...
<p>I'd do it this way:</p> <p>find columns of <code>object</code> dtype:</p> <pre><code>obj_cols = df[col_names].columns[df[col_names].dtypes.eq('object')] </code></pre> <p>convert them to numeric dtypes, replacing NaN's with <code>0</code> (zero):</p> <pre><code>df[obj_cols] = df[obj_cols].apply(pd.to_numeric, err...
python|pandas|scikit-learn
3
357,495
49,790,058
extract columns by index and name at same time
<pre><code>FEATURES = ['col_0', 'col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7'] DATA_TYPE = [True, True, False, True, False, False, True, True, False, True] </code></pre> <p>Here are my masks examples.</p> <pre><code>train_data.iloc[:, DATA_TYPE].loc[:, FEATURES] </code></pre> <p>I first get all colum...
<p>First filter columns by <code>DATA_TYPE</code> by indexing and then get all filtered columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>intersection</code></a>:</p> <pre><code>np.random.seed(456) train_data = pd.DataFrame(np.ran...
python-3.x|pandas|numpy
0
357,496
49,517,822
tensorflow GPU based installation
<p>My system is ubuntu 16.04 version my laptop is <a href="https://www.digit.in/laptops/dell-inspiron-15r-5521-w540202in8-price-1746.html" rel="nofollow noreferrer">dell Inspiron-5521</a> and it has intel graphic card but tensorflow needs nvidia graphics for cuda support.</p> <p>Is there any way where i can run tensor...
<p>To run <code>tensorflow-gpu</code> you need nvidia card. You'll need to stick to running normal tensorflow on CPU. <a href="https://stackoverflow.com/questions/40000518/is-intel-based-graphic-card-compatible-with-tensorflow-gpu">Is Intel based graphic card compatible with tensorflow/GPU?</a></p>
python|tensorflow
1
357,497
49,518,655
Averaging values between files, but keeping non-matching values
<p>I have two files: </p> <p>File 1:</p> <pre><code>key.1 10 6 key.2 5 6 key.3. 5 8 key.4. 5 10 key.5 4 12 </code></pre> <p>File 2: </p> <pre><code>key.1 10 6 key.2 6 6 key.4 5 10 key.5 2 8 </code></pre> <p>I have a rather complicated issue. I want to average bet...
<p>The following solution uses Pandas, and assumes that your data is stored in plain text files 'file1.txt' and 'file2.txt'. Let me know if this assumption is incorrect - it is likely a minimal edit to alter for different file types. If I have misunderstood your meaning of the word 'file' and your data is already in Da...
python|pandas|dataframe
4
357,498
49,788,418
Use pandas to partially unpivot a table
<p>Here is a table, need to partially unpivot it by class.</p> <pre><code>ID Class Type 2017 2018 12A A Net 1 7 12B A Gross 8 12A B Net 3 9 12B B Gross 4 10 13A A Net 5 11 13C B Net 6 5 </code></pre> <p>The expected...
<p>Use:</p> <pre><code>df1 = df.set_index(['ID','Type','Class']).unstack().sort_index(level=1, axis=1) df1.columns = ['{}{}'.format(a,b) for a, b in df1.columns] df1 = df1.reset_index() s = df.drop_duplicates('ID').set_index('ID')['Class'] df1.insert(1, 'Class', df1['ID'].map(s)) print (df1) ID Class Type 2017...
python|pandas
1
357,499
49,496,389
change all values of pandas dataframe based on condition?
<p>Consider the following example pandas dataframe, </p> <pre><code> col1 col2 col3 0 1 3 9 1 2 4 0 </code></pre> <p>how can I take all values larger than 0.5 and convert them into 1 without a for loop? In this toy example, the resulting dataframe should be </p> <pre><code> col1 col2 ...
<p>Or:</p> <pre><code>(df&gt;.5).mul(1) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 0 1 1 1 1 1 1 0 </code></pre> <p>Faster:</p> <pre><code>pd.DataFrame((df.values&gt;.5), index=df.index, columns=df.columns, dtype=np.int) </code></pre> <h1>Timings</h1> <pre><code>%timeit df.mask(df...
pandas
2