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 |
|---|---|---|---|---|---|---|
369,300 | 68,499,637 | Randomly get index of one of the maximum values in a PyTorch tensor | <p>I need to perform something similar to the built-in torch.argmax() function on a one-dimensional tensor, but instead of picking the index of the first of the maximum values, I want to be able to pick a random index of one of the maximum values. For example:</p>
<pre><code>my_tensor = torch.tensor([0.1, 0.2, 0.2, 0.1... | <p>You can get the indexes of all the maximums first and then choose randomly from them:</p>
<pre><code>def rand_argmax(tens):
max_inds, = torch.where(tens == tens.max())
return np.random.choice(max_inds)
</code></pre>
<p>sample runs:</p>
<pre><code>>>> my_tensor = torch.tensor([0.1, 0.2, 0.2, 0.1, 0.1... | python|python-3.x|pytorch | 2 |
369,301 | 68,534,160 | How can I use a Cloud TPU with Tensorflow Lite Model Maker? | <p>I'm training an object detection model (EfficientDet-Lite) using Tensorflow Lite Model Maker in Colab and I'd like to use a Cloud TPU. I have all the images in a GCS bucket and provide a CSV file. When I call object_detector.create I get the following error:</p>
<pre><code>/usr/local/lib/python3.7/dist-packages/tens... | <p>Yeah the error is happening with TFHub, which seems to be well known. Basically TF Hub loading tries to use a local cache which TPU doesn't have access to (and the Colab doesn't even provide). Check out <a href="https://github.com/tensorflow/hub/issues/604" rel="nofollow noreferrer">https://github.com/tensorflow/hub... | tensorflow|google-colaboratory|tensorflow2.0|tensorflow-lite|google-cloud-tpu | 1 |
369,302 | 68,477,333 | Using custom function for Pandas Rolling Apply that depends on colname | <p>Using Pandas 1.1.5, I have a test DataFrame like the following:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'id': ['a0','a0','a0','a1','a1','a1','a2','a2'],
'a': [4,5,6,1,2,3,7,9],
'b': [3,4,5,3,2,4,1,3],
'c': [7,4,3,8,9,7,4,6],
... | <p>I wouldn't be surprised if there's a "better" solution, but I think could at least be a "good start" (I don't do a whole lot with <code>.rolling(...)</code>).</p>
<p>With this solution, I make two critical assumptions:</p>
<ol>
<li>All <code>denom_<X></code> have a corresponding <code><X... | python|pandas|apply|rolling-computation | 1 |
369,303 | 68,603,926 | issue with installing pandas on python 3.9.6 windows visual studio code | <p>I am using python 3.9.6 on windows
I am trying to install pandas through the terminal (Visual studio code)
by typing</p>
<pre><code>pip install pandas
</code></pre>
<pre><code>pip3 install pandas
</code></pre>
<pre><code>pip3.9 install pandas
</code></pre>
<pre><code>pip3.9.6 install pandas
</code></pre>
<p>All of t... | <p>The errors in your image show that there is an issue with your Internet connection. It is likely you are behind a proxy. Try using a VPN as long as it won't get you in trouble (if you are at work or school?)</p>
<p>If you cannot connect to some other wifi or if you cannot fix the proxy if it resides on your local co... | python|pandas|pip | 0 |
369,304 | 68,821,001 | Optimize calculations involving a Pandas series | <p>I'm trying to do some calculations involving a pandas series as shown below. Basically first I extracted t from a DataFrame column and then used a for loop with "if...else..." to do further calculation, because I found out that when I used max(f_min, nan), f_min was always returned. The code below worked, ... | <p>Let's use either:</p>
<pre><code>d.clip(f_min,)
</code></pre>
<p>or</p>
<pre><code>d.loc[d<f_min] = f_min
</code></pre> | pandas|series|calculation | 1 |
369,305 | 68,613,816 | how do you pass text to tensorflow model to return prediction | <p>New to tf/python and have created a model that classifies text with a toxicity level (obscene, toxic, threat, etc). This is what I have so far and it does produce the summary, so I know it is loading correctly. How do I pass text to the model to return a prediction? Any help would be much appreciated.</p>
<pre><code... | <p>It needs to be processed in the same way. This can be done with:</p>
<pre><code>inputs = [
"tenserflow seems like it fits the bill but there are zero tutorials that outline
how to reuse a model in a production environment"]
sequence = tokenizer.texts_to_sequences(inputs) # same tokenizer which is used o... | python|python-3.x|tensorflow|tensorflow2.0|tf.keras | 2 |
369,306 | 68,625,478 | How to perform excel calculation using python pandas | <p>I have been using pandas library for data manipulation. And I am stuck somewhere while doing the below calculation.</p>
<p>I have below table in my excel file which contains two columns and I need to create third column (cap). I need to do this excel calculation of third column in my program using python pandas.</p>... | <p>Assuming the "period" column in dataframe has already been converted to the datetime object, then by simply defining custom function and using df.apply() would most likely do your job.</p>
<p>Example: (please also change the custom function correctly since I did not include multiply by the cap value below ... | python|pandas|numpy | 1 |
369,307 | 36,516,776 | In Pandas, how to get the number of unique values, up to time T? | <p>consider the following dataset</p>
<pre><code>df=pd.DataFrame({'A':pd.date_range('2012-02-02','2012-02-07'),
'ID':['A','B','A','D','A',np.NaN]})
df
Out[122]:
A ID
0 2012-02-02 A
1 2012-02-03 B
2 2012-02-04 A
3 2012-02-05 D
4 2012-02-06 A
5 2012-02-07 NaN
</code... | <p><code>apply</code> a lambda that slices the df using <code>loc</code> and the row index value using <code>.name</code> and calcs the <code>nunique</code> count of ID column:</p>
<pre><code>In [5]:
df['Unique_ID'] = df.apply(lambda x: df['ID'].loc[:x.name].nunique(),axis=1)
df
Out[5]:
A ID Unique_ID
0 ... | python|pandas | 3 |
369,308 | 36,538,750 | Pandas how to get a list of rows that have multiple values for an index level in a Multiindex DataFrame | <p>I got this Dataframe from a pivot operation and I dont know how to handle "nested" or multiindex Dataframes in pandas. </p>
<p>The Dataframe looks like this example below, only there are many more rows than shown here.
[edit: Added an additional "chr18" row to give a more illustrative example. This too needs to be... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by second level of <code>MultiIndex</code> <code>chrom</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel... | python|pandas | 1 |
369,309 | 36,611,043 | Itereating over an image with backtracking | <p>So I asked <a href="https://stackoverflow.com/questions/36585243/coloring-only-the-inside-of-a-shape?noredirect=1#comment60802570_36585243">this question</a> and in one of the comments someone suggested </p>
<blockquote>
<p>I don't see why you can't just start in the corner and walk through every pixel on the out... | <p>If I have understood correctly You want to start in the corner of an image and set every pixel outside of any shape to <code>black</code>, lets give it a value <code>1</code>. So after this procedure You will have an array with inner pixels in every shape set to <code>white</code> or <code>0</code> and every outer o... | python|image|numpy|iteration | 1 |
369,310 | 36,389,919 | Chaining grouping, filtration and aggregation | <p><code>DataFrameGroupby.filter</code> method filters the groups, and returns the <code>DataFrame</code> that contains the rows that passed the filter.</p>
<p>But what can I do to obtain a new <code>DataFrameGroupBy</code> object instead of a <code>DataFrame</code> after filtration?</p>
<p>For example, let's say I h... | <p>You can do it this way:</p>
<pre><code>In [310]: df
Out[310]:
a b
0 1 4
1 7 3
2 6 9
3 4 4
4 0 2
5 8 4
6 7 7
7 0 5
8 8 5
9 8 7
10 6 1
11 3 8
12 7 4
13 8 0
14 5 3
15 5 3
16 8 1
17 7 2
18 9 9
19 3 2
20 9 1
21 1 2
22 0 3
23 8 9
24 7 7
25 8 1
26 5 8
27... | python|python-3.x|pandas|dataframe|grouping | 4 |
369,311 | 36,627,601 | reshape dataframe from multiple columns to one | <p>I have a dataframe like this</p>
<pre><code>2014-11-26 09:05:19.669 -0.000610 0.000000 -0.001526 -0.000610 -0.000305
2014-11-26 09:05:20.169 -0.000610 -0.000610 0.000305 -0.000610 -0.000610
2014-11-26 09:05:20.669 -0.001831 -0.000916 -0.000610 0.000610 -0.000305
2014-11-26 09:05:21.169 -0.000916 -0.0003... | <p>Exact syntax can vary here depending on exactly how you begin. I'm starting with the default index and the times are stored in a column 'index' and are of type datetime</p>
<pre><code>>>> df
index x y z
0 2014-11-26 09:05:19.669 -0.000610 0.000000 -0.001526
1 ... | python|pandas | 1 |
369,312 | 36,620,029 | Python (pandas) - reset index with count | <p>I have a DataFrame:</p>
<pre><code> HH PERSON SPOT WEIGHT
1002141 aa 1 1332.25
1011831 ab 1 2083.31
1031726 aa 1 2589.09
1042819 aa 1 4736.28
1043006 aa 1 1588.39
1043006 aa 1 1588.39
1060911 aa 1 1113.97
1001665 aa 2 32... | <p>You can use <code>transform</code> for this to add a count column which is just the group size in this case:</p>
<pre><code>In [164]:
df['Count'] = df.groupby(['HH','PERSON','SPOT'])['WEIGHT'].transform('size')
df
Out[164]:
HH PERSON SPOT WEIGHT Count
0 1002141 aa 1 1332.25 1
1 1011831 ... | python|pandas|group-by | 1 |
369,313 | 36,512,065 | Python: extracting data values from one file with IDs from a second file | <p>I’m new to coding, and trying to extract a subset of data from a large file.
File_1 contains the data in two columns: <code>ID</code> and <code>Values</code>.
File_2 contains a large list of IDs, some of which may be present in File_1 while others will not be present.
If an ID from File_2 is present in File_1, I w... | <p>You can do it using a simple dictionary in Python. You can make a dictionary from file 1 and read the IDs from File 2. The IDS from file 2 can be checked in the dictionary and only the matching ones can be written to your output file. Something like this could work :</p>
<pre><code>with open('data.csv','r') as f:
... | python|python-2.7|pandas | 0 |
369,314 | 36,457,130 | Neural net optimization failing (using Scipy fmin_cg) | <p>Just a bit of context: I'm attempting to implement a 3 layer neural network (1 hidden layer) for image classification on the Cifar-10 dataset. I've implemented backpropagation and originally tried training the network simply using gradient descent, but my cost was plateauing around 40 or so (which effectively classi... | <blockquote>
<p>It seems to me that the function is attempting to take the dot product of the same vector, which doesn't make any sense to me.</p>
</blockquote>
<p>This is not how <code>numpy.dot</code> works. The problem is exactly what the error message says: it tries to perform a matrix multiplication and fails ... | python|numpy|scipy|neural-network|backpropagation | 1 |
369,315 | 36,532,585 | Passing an array to numpy.dot() in Python implementation of Perceptron Learning Model | <p>I'm trying to put together a Python implementation of a single-layer Perceptron classifier. I've found the example in Sebastian Raschka's book 'Python Machine Learning' very useful, but I have a question about one small part of his implementation. This is the code:</p>
<pre><code>import numpy as np
class Percep... | <p>Your concern seems to be why is X in net_input and predict defined as an array not a vector (I'm assuming your definitions are what i mentioned in the comment above--really though i would say that there is no distinction in this context)... What gives you the impression that X is an 'array' as opposed to a 'vector'?... | python|arrays|numpy|classification|perceptron | 0 |
369,316 | 36,363,238 | Selecting a column of a numpy array | <p>I am somewhat confused about selecting a column of an NumPy array, because the result is different from Matlab and even from NumPy matrix. Please see the following cases.</p>
<p>In <strong>Matlab</strong>, we use the following command to select a column vector out of a matrix.</p>
<pre><code>x = [0, 1; 2 3]
out = ... | <p>In MATLAB everything has atleast 2 dimensions. In older MATLABs, 2d was it, now they can have more. <code>np.matrix</code> is modeled on that old MATLAB.</p>
<p>What does MATLAB do when you index a 3d matrix?</p>
<p><code>np.array</code> is more general. It can have 0, 1, 2 or more dimensions.</p>
<pre><code>x[... | python|arrays|numpy|matrix|vector | 13 |
369,317 | 36,261,334 | Print the raw value of a column alone, in pandas? | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame([ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}])
</code></pre>
<p>Now I want to retrive George's age:</p>
<pre><code>df[df.name == 'george'].age
</code></pre>
<p>But this outputs some extra information along with the raw value:</p>
<pre><code>... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow noreferrer"><code>values</code></a> for converting <code>Serie... | python|pandas | 11 |
369,318 | 36,446,182 | Writing csv reader to excel using python | <p>I want to write the csv (huge) data to excel file using python.
I have read the csv file using csv.reader like-</p>
<pre><code>with open(main_path+i_bu_name+"/"+str(snapshot_id)+"/"+input_folder+input_csv_name,'rb') as input:
print "entering file read"
reader=csv.reader(input)
... | <p>You should use Value property:</p>
<pre><code>Worksheets("Sheet1").Range("A1:A5").Value = [1, 2, 3, 4, 5]
</code></pre> | python|excel|pandas|dataframe|win32com | 0 |
369,319 | 36,653,781 | Create a class with a "ndarray" attribute | <p>I want to create a class that looks like this :</p>
<pre><code>class MyStructure:
def __init__(self, ndarray_type):
self.data = ndarray_type
</code></pre>
<p>And I want to pass an object of this class as an argument to other classes. For example :</p>
<pre><code>class Edit:
def __init__(self, stru... | <p><code>image</code> is an instance of <code>MyStructure</code> which does not implement <code>[..]</code> access. You have to implement a <code>__getitem__</code> method of <code>MyStructure</code> which forwards this access to your <code>data</code> attribute to enable this:</p>
<pre><code>class MyStructure:
de... | python|numpy | 0 |
369,320 | 36,589,998 | why is numba so much faster on this simple summation? | <p>I have a public notebook where python, numpy, numba, cython, and fortran are compared on simple summation:</p>
<p><a href="https://gist.github.com/denfromufa/7727874c4fe1e7e174ed953930e93bbc" rel="nofollow">https://gist.github.com/denfromufa/7727874c4fe1e7e174ed953930e93bbc</a></p>
<p>Why is numba so much faster?<... | <p>As pointed out by @DavidW, you aren't really doing a comparison of identical algorithms. Below I've written two separate functions for each cython and numba that do the same thing. The first operates on an array, the second is just given an integer:</p>
<p>Cython:</p>
<pre><code>cpdef long cy_sum(long[:] A):
c... | python|numpy|cython|numba|f2py | 3 |
369,321 | 36,628,277 | in Pandas, how to create a variable that is n for the nth observation within a group? | <p>consider this</p>
<pre><code>df = pd.DataFrame({'B': ['a', 'a', 'b', 'b'], 'C': [1, 2, 6,2]})
df
Out[128]:
B C
0 a 1
1 a 2
2 b 6
3 b 2
</code></pre>
<p>I want to create a variable that simply corresponds to the ordering of observations after sorting by 'C' within each <code>groupby('B')</code> group.... | <p>I think you can use <code>range</code> with <code>len(df)</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],
'B': ['a', 'a', 'b'],
'C': [5, 3, 2]})
print df
A B C
0 1 a 5
1 2 a 3
2 3 b 2
df.sort_values(by='C', inplace=True)
#or witho... | python|pandas | 3 |
369,322 | 5,251,127 | pyplot of array crashes | <p>I am attempting to plot array values obtained from summing individual columns of a numpy array.
Working on Win XP, Python 2.5, matplotlib-1.0.1, numpy-1.5.1, PIL-1.1.7
Here is the code:</p>
<pre><code>import Image
import numpy as np
import matplotlib.pyplot as plt
im = Image.open("tish.pnm")
im = im.convert("1") #... | <p>It should also be noted, that besides the fact that you are attempting to plot a dict rather than a numpy array (this is why your code is producing an error), that you could achieve the same results without using an explicit python loop by using</p>
<pre><code>sums = np.sum(data,axis=0)
</code></pre>
<p>and then p... | python|numpy|matplotlib | 0 |
369,323 | 5,347,091 | Slicing NumPy array representing nested list | <p>I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.</p>
<p>Here's the example:</p>
<pre><code>import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist()... | <p>What you are doing is multi-axis slicing. Because <code>l</code> is a two dimensional array and you wish to slice the second dimension you use a comma to indicate the next dimension.</p>
<p>the <code>, 0:2</code> selects the first two elements of the second dimension.</p>
<p>There's a really nice explanation <a hre... | python|numpy|slice | 18 |
369,324 | 5,183,533 | How to make List from Numpy Matrix in Python | <p>I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:</p>
<p>[[ 0.16666667 0.66666667 0.16666667]]</p>
<p>which is of type:</p>
<pre><code><class 'numpy.matrixlib.defmatrix.matrix'>
</code></pre>
<p>how can I convert this to a list. B... | <p>May not be the optimal way to do this but the following works:</p>
<pre><code>a = numpy.matrix([[ 0.16666667, 0.66666667, 0.16666667]])
list(numpy.array(a).reshape(-1,))
</code></pre>
<p>or</p>
<pre><code>numpy.array(a).reshape(-1,).tolist()
</code></pre>
<p>or</p>
<pre><code>numpy.array(a)[0].tolist()
</code><... | python|list|matrix|numpy | 45 |
369,325 | 53,316,471 | Pandas Dataframes.to_csv truncates long values | <p><strong>Problem:</strong> I'm trying to store big datasets using Pandas dataframes in python. My trouble is that when I try to save it to csv, chunks of my data is being trunctated, as such:</p>
<blockquote>
<p>e+12</p>
<p><strong>and</strong></p>
<p>[value1 value2 value3 <strong>. . .</strong> value1853 value1854]<... | <p>Changing the data type as @Jacob Tomlinson said solves one problem, looking into numpys array2string solved the other.</p>
<p>Adding <code>np.set_printoptions(threshold=np.nan)</code> stops to_csv from truncating the output strings.</p>
<pre><code>dframe = pd.DataFrame()
arr = np.array([])
for x in range(123456789... | python|pandas|dataframe | 4 |
369,326 | 53,093,983 | Why does sklearn's train/test split plus PCA make my labelling incorrect? | <p>I am exploring PCA in Scikit-learn (0.20 on Python 3) using Pandas for structuring my data. When I apply a test/train split (and only when), my input labels seem to no longer match up with the PCA output.</p>
<pre><code>import pandas
import sklearn.datasets
from matplotlib import pyplot
import seaborn
def load_bc_... | <p>The issue has three parts:</p>
<ol>
<li>The shuffling in <code>train_test_split()</code> causes the indices in <code>bc_train</code> to be in a random order (compared to the row location).</li>
<li>PCA operates on numerical matrices, and effectively strips the indices from the input. Creating a new <code>DataFrame<... | python|pandas|scikit-learn|pca | 1 |
369,327 | 53,150,298 | Concat certain columns to one with no standard number of columns in each loop | <p>I have a dictionary:</p>
<pre><code>#file1 mentions 2 columns while file2 mentions 3
dict2 = ({'file1' : ['colA', 'colB'],'file2' : ['colY','colS','colX'], etc..})
</code></pre>
<p>I want to do a concatenation of the mentioned columns in a new column for each file.
This should be automated.</p>
<pre><code>for k, ... | <p>I believe you need change:</p>
<pre><code>df['new'] = df['first_col'].astype(str) + df['second_col']
</code></pre>
<p>to converting all columns to strings and then <code>join</code> them with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code... | python|pandas | 1 |
369,328 | 53,328,043 | Pandas reshape dataframe values as columns | <p>I am struggling with a problem.</p>
<p>I have a pandas dataframe that looks like this:</p>
<pre><code>month code a b c
2018-01-01 foo 43 34324 12
2018-01-01 bar 232 34 634
2018-01-01 gar 2312 454 243
2017-01-01 foo 12 1234 34534
2017-01-01 bar 32 34232 34... | <p>Looks like you need</p>
<pre><code>df.groupby('month').sum().T
</code></pre>
<h3>Explanation:</h3>
<ol>
<li>Group by unique month.</li>
<li>Within each group, take the <code>sum</code> of each column, which by default will select only columns with numeric data types. That's why the column <code>code</code> does n... | python|pandas | 3 |
369,329 | 52,937,718 | Pandas groupby multiple columns, count, and resample | <p>Having the following dataframe:</p>
<pre><code> UserID TweetLanguage
2014-08-25 21:00:00 001 english
2014-08-27 21:04:00 001 arabic
2014-08-29 22:07:00 001 espanish
2014-08-25 22:09:00 002 english
2014-08-26 22:09:00 002 espanish
2014-08-25 22:09:00 003 ... | <pre><code>df.groupby([pd.Grouper(freq='W'), 'User ID'])['TweetLanguage'].nunique().unstack().plot()
</code></pre> | python|pandas|pandas-groupby | 3 |
369,330 | 53,154,628 | datetime.datetime.strptime to convert a string to datetime it occurs the mistakes unconverted date remands: 2 | <p>The csv file has 18 columns and 6 columns of them are 'year','month','day','hours','minutes','seconds', whose data type are all INT,except the columns 'seconds' is float.</p>
<p>Firstly, I have converted the int and float type to string, and then concated them, then used <code>the datetime.datetime.strptime</code>... | <p>You are overthinking this with Pandas. If your columns are appropriately named, you can feed directly to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a>. In addition, avoid using Python's <code>datetime</code> module w... | python|python-2.7|pandas|datetime | 1 |
369,331 | 52,970,820 | Setting an Explicit start of Week in Pandas DateTime module | <p>I've been searching through SO and the pandas documentation with little success.</p>
<p>I'm attempting to find a way to set an explicit start of week and end of week in pandas datetime</p>
<p>basically I want my week to start on Saturday and end on Friday. </p>
<p>take the following df</p>
<pre><code> import pa... | <p>You can shift <code>2</code> days:</p>
<pre><code>df['Week'] = pd.DatetimeIndex(df['Dates']).shift(2, freq='d').week
print(df)
Dates Week
0 2018-10-20 43
1 2018-10-19 42
</code></pre> | python|pandas | 3 |
369,332 | 53,200,036 | Loop to perform operation on i+1 in numpy array | <p>I have a numpy array, I'd like to take the 3 numbers in each row, minus them from the next row and store those values in another array.</p>
<p>something like</p>
<pre><code>for i in array:
a = i - i+1
</code></pre>
<p>I know this is very wrong, but at least this gives the idea of what I want.</p>
<p>Obviousl... | <p>IIUC, instead of looping, you can just shift your arrays 1 up using <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.roll.html" rel="nofollow noreferrer"><code>np.roll</code></a>, subtract that from your original input, and take all the resulting arrays except the last (because there will b... | arrays|loops|numpy|iteration | 0 |
369,333 | 53,300,244 | Prevent NaN to become index and column in dataframe pivot | <p>I have a dataframe which I extend to include values for all increments in 2 columns. Therefor NaN values are introduced, as expected and desired. </p>
<p>However, when I use pivot on this dataframe I'll get a row and column for NaN.
Can I prevent this when doing the pivot? If not, how can I drop a column named NaN... | <p>For me working <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code></a> by missing value <code>np.nan</code>:</p>
<pre><code>data = (df.pivot("Y","X","Z")
.sort_values(by=['Y'],ascending=False)
.drop(np.nan, axis=1)
... | python|pandas|dataframe|pivot | 1 |
369,334 | 53,294,889 | Subtract a column vector from matrix at specified vector of columns using only broadcast | <p>I want to subtract a column vector from a numpy matrix using another vector which is index of columns where the first column vector needs to be subtracted from the main matrix. For eg.</p>
<pre><code>M = array([[ 1, 2, 1, 1],
[ 2, 1, 1, 1],
[ 1, 1, 2, 1],
[ 2,... | <p>One can use <code>bincount</code> and <code>outer</code></p>
<pre><code>>>> M - np.outer(V, np.bincount(I, None, M.shape[1]))
array([[ 0, 1, 0, -3],
[ 1, 0, 0, -3],
[ 0, 0, 1, -3],
[ 1, 0, 0, -3],
[ 0, 0, 0, -2]])
</code></pre>
<p>or <code>subtract.at</code></p>
<pre... | python|numpy|matrix|array-broadcasting | 4 |
369,335 | 53,174,254 | Variable types in TensorFlow | <p>I have a model with several variable types. </p>
<ul>
<li>boolean flag: 0 or 1</li>
<li>positive float value: strictly greater than zero and known max < 1000</li>
<li>integer: 1 < value < 12 </li>
<li>categorical input: "AA","AB",.., "ZZ" - only about 100 values are observed</li>
<li><p>Integer score as ... | <p>For the categorical variables, you're going to need to transform them into a numeric representation, either by a one-hot encoding (<a href="https://hackernoon.com/what-is-one-hot-encoding-why-and-when-do-you-have-to-use-it-e3c6186d008f" rel="nofollow noreferrer">https://hackernoon.com/what-is-one-hot-encoding-why-an... | tensorflow-datasets | 1 |
369,336 | 53,196,467 | Can you post process results from Cloud ML's prediction output? | <p>I have a model for object detection (Faster RCNN from Tensorflow's Object Detection API) running on Google Cloud ML. I also have some code to filter the resulting bounding boxes based on size, aspect ratio etc.</p>
<ol>
<li><p>Is it possible to run this code as part of the prediction process so I don't need to run ... | <ol>
<li>You can simply add your filter logic to prediction process code and deploy it back.</li>
<li>Yes you can use <strong>min_score_thresh</strong> argument in <strong>visualize_boxes_and_labels_on_image_array</strong>. use below code</li>
</ol>
<blockquote>
<pre><code>vis_util.visualize_boxes_and_labels_on_image_... | python|tensorflow|google-cloud-ml | 1 |
369,337 | 53,259,647 | Issues in upgrading ML libraries using AWS Sagemaker Notebook's Lifecycle configurations | <p>I use the following script to automate upgrading of my libraries.</p>
<p><strong>My script (Start Notebook):</strong></p>
<pre><code>#!/bin/bash
set -e
echo 'Before:'
echo $PATH
export PATH=/home/ec2-user/anaconda3/envs/JupyterSystemEnv/bin:/home/ec2-user/anaconda3/bin/:/usr/libexec/gcc/x86_64-amazon-linux/4.8.... | <p>Looks like <code>pip install</code> in your case executed "outside" of virtualenv </p>
<p>try to change from: </p>
<p><code>source /home/ec2-user/anaconda3/bin/activate tensorflow_p36</code> </p>
<p>to: </p>
<p><code>source /home/ec2-user/anaconda3/bin/activate tensorflow_p36 && pip install pandas ten... | python|tensorflow|keras|amazon-sagemaker|amazon-machine-learning | 2 |
369,338 | 53,241,848 | Changing a column value in pandas dataframe excluding the tail in group by | <p>Let's take an example of a python dataframe.</p>
<p><strong>ID Age Bp</strong></p>
<p>1 22 1</p>
<p>1 22 1</p>
<p>1 22 0</p>
<p>1 22 1</p>
<p>2 21 0</p>
<p>2 21 1</p>
<p>2 21 0</p>
<p>In the above code, the last n series for column BP (lets consider n to be 2) with group by ID sh... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> with <code>ascending=False</code> for counter from back per groups and assign <code>0</code> with <a href="https://docs.scipy.org/doc/numpy/reference/gener... | python|pandas | 2 |
369,339 | 53,178,018 | Average of elements in a subarray | <p>I have an array like <code>a=[1, 2, 3, 4, 5, 6, 7]</code>. I want to split this array into 3 chunks of any size.</p>
<p>When I split this into 3 chunks, I get 3 subarrays: <code>[array([1, 2, 3]), array([4, 5]), array([6, 7])]</code>. </p>
<p>My goal is to get an array with the average of the elements in a subarra... | <p>Here's a vectorized solution that avoids the splitting step to gain performance and directly gets the grouped summations and hence averages -</p>
<pre><code>def average_groups(a, N): # N is number of groups and a is input array
n = len(a)
m = n//N
w = np.full(N,m)
w[:n-m*N] += 1
sums = np.add.re... | python|arrays|numpy|split|average | 4 |
369,340 | 53,032,922 | TensorFlow while loop with condition dependent on body | <p>I want to have a while loop with the condition dependent on a tensor computed in the loop body, but I don't know how to accomplish this with <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="nofollow noreferrer"><code>tf.while_loop()</code></a>.</p>
<p>My input processing includes random cropp... | <p>The arguments that are passed on to the <code>condition</code> function are the arguments returned from your <code>body</code> function. So you just have to return that value that you want to base your condition on in the <code>body</code> function, then carry out the condition on that value in your <code>cond</code... | python|tensorflow|while-loop | 2 |
369,341 | 53,074,607 | Efficiently resize batch of np.array images | <p>I have a 4D np.array size (10000,32,32,3) that represents a set of 10000 RGB images.</p>
<p>How can I use <code>skimage.transform.resize</code> or other function to resize all images efficiently so that the (32,32) is interpolated to (224,224)? I'd prefer to do this with skimage, but I'm open to any solutions that ... | <p>I won't likely accept my own answer, but it seems that a simple for loop is actually fairly fast (says ~300% cpu utilization from <code>top</code>).</p>
<pre><code>from skimage.transform import resize
imgs_in = np.random.rand(100, 32, 32, 3)
imgs_out = np.zeros((100,224,224,3))
for n,i in enumerate(imgs_in):
... | python|python-3.x|tensorflow|image-resizing|scikit-image | 6 |
369,342 | 52,983,912 | How to select columns from the dataframe based on variables from another dataframe | <p>I wanted to select only those columns from df2 which are equal to the variables of df1 in python pandas</p>
<p>df1 </p>
<pre><code>parameter (column name)
a
b
c
</code></pre>
<p>df2</p>
<pre><code>w x a c z
3 1 5 6 1
5 67 4 3 56
8 12 6 1 23
</code></pre>
<p>my expected output is</p>
<pre><code>a... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>intersection</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow noreferrer"><code>isin</code></a> for boolean mask:</p>
<... | python|pandas|dataframe | 1 |
369,343 | 53,079,901 | How to build an image processing model with new dataset using machine learning (Tensorflow)? | <p>I want to extract the data shown on an instrument panel cluster of a bike using image processing and ML (mostly Tensorflow). The sample of such cluster is </p>
<p><img src="https://i.stack.imgur.com/IJFDg.jpg" alt="here">.</p>
<p>My input will be such complete image and I want to get the data such as speed shown b... | <p>There are a few things to consider here. You will first want to process the image a little before feeding it into a neural network for instance. Maybe crop out the section which contains the speedometer reading and perform some kind of OCR (Optical Character Recognition) on it for the speed reading.</p>
<p>The neut... | python|tensorflow|image-processing|machine-learning | 3 |
369,344 | 53,078,707 | Dataframe operation | <p>I have a dataframe populated with different zeros and values different than zero. For each row I want to apply the following condition:</p>
<p>If the value in the given cell is different than zero AND the value in the cell to the right is zero, then put the same value in the cell to the right. </p>
<p>The example ... | <p>Since you imply you are using Pandas, I would leverage a bit of the build-in muscle in the library.</p>
<pre><code>import pandas as pd
import numpy as np
s = pd.Series([0,0,0,20,0,0,0,33,3,0,5,0,0,0,0,0])
s.replace(0, np.NaN, inplace=True)
s = s.ffill()
</code></pre>
<p>Output:</p>
<pre><code>0 NaN
1 N... | python|python-3.x|pandas|dataframe | 0 |
369,345 | 52,957,451 | Pandas read csv converts float to Nan | <p>I'm trying to read a csv file via pandas with following data (excerpt from <a href="https://data.worldbank.org/indicator/NY.GDP.MKTP.CD" rel="nofollow noreferrer">https://data.worldbank.org/indicator/NY.GDP.MKTP.CD</a>) </p>
<pre><code>"Afghanistan","AFG","GDP (current US$)","NY.GDP.MKTP.CD","537777811.111111"
"Bur... | <p>You can manually tell Pandas to use specific datatype for specific column.</p>
<pre><code>import np
...your code...
#Let's say you name your columns:
COL_NAMES=['Country','CountryCode','GDP_Type','WhateverField','GDP']
# you can specify datatype for a single column and let Pandas guess the rest:
COL_TYPES={'GDP':np... | python|pandas|csv | 0 |
369,346 | 53,097,952 | How to understand numpy strides for layman? | <p>I am currently going through numpy and there is a topic in numpy called "strides". I understand what it is. But how does it work? I did not find any useful information online. Can anyone let me understand in a layman's terms?</p> | <p>The actual data of a numpy array is stored in a homogeneous and contiguous block of memory called data buffer. For more information see <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/internals.html" rel="noreferrer">NumPy internals</a>.
Using the (default) <a href="https://en.wikipedia.org/wiki/Row-_and... | python|numpy|scipy|stride | 104 |
369,347 | 53,031,442 | Creating a new column based on the element of next row of existing column | <p>I am working on cleaning up and re-structured the data frame.</p>
<p>I have the following dataframe:</p>
<pre><code>data= pd.DataFrame()
data['ID'] = [1,1,1,1,1,2,2,2,2,2]
data ['EventSecond'] = [1.5,2,2.5,3,3.8,4,4.8,6,7,8,]
data ['P1'] = ['A','B','C','D','E','F','A','D','E','G']
data ['Code'] = [12,13,16,9,9,0,4... | <p>IIUC, you need <code>groupby</code> and <code>transform</code>:</p>
<pre><code>mask = (data['status'].isin(['Pass','pass']))
data.loc[mask,'P2'] = data[mask].groupby('ID')['P1'].transform(lambda x: x.shift(-1))
data.loc[data['Accuracy']=='Not Accurate','P2'] = np.nan
</code></pre>
<p>OR using only filters:</p>
<p... | python|pandas | 2 |
369,348 | 53,321,027 | How to Join CSV in Python Pandas Comparing 2 CSV | <p>I have 2 csv files lets say <strong>A.csv</strong> and <strong>B.csv</strong>. A.csv has columns a,b,c,d and B.csv has columns x,y,z,t. I want to search that if an entry in column a exist in column x then print z and d if that rows.</p>
<p>Like,</p>
<pre><code>for each i in A
if A.[a][i] exist in B.x
pr... | <p>Imagine your csv data file looks like below:</p>
<pre><code>print(df1)
A B C D
0 1 4 7 4
1 2 5 8 5
2 3 6 9 8
print(df2
X Y Z T
0 1 11 6 8
1 5 12 8 0
2 2 13 0 4
</code></pre>
<p>A simple merge would solve your problem, considering Left table is df1... | python|pandas|csv|numpy | 2 |
369,349 | 53,039,824 | Accessing data in Pandas dataframe | <p>So I have a pandas dataframe and this is how it looks like:</p>
<p>This is a paragraph [if-statement, for-loop]</p>
<p>This is a second paragraph [for-loop, java]</p>
<p>To explain, the left column serves as text-data and the right column classifies what the text-data is about. </p>
<p>I want t... | <p>IIUC need:</p>
<pre><code>df = pd.DataFrame({'col1':['This is a paragraph','This is a second paragraph'],
'col2':[['if-statement', 'for-loop'],['for-loop','java']]})
df = df[df['col2'].apply(lambda x: 'java' in x)]
#alternative solution
#df = df[['java' in x for x in df['col2']]]
</code></pre>
... | python|pandas | 1 |
369,350 | 53,179,034 | How to perform element wise operation on two sets of columns in pandas | <p>I have the dataframe:</p>
<pre><code> c1 | c2 | c3 | c4
5 | 4 | 9 | 3
</code></pre>
<p>How could I perform element wise division (or some other operation) between c1/c2 and c3/c4</p>
<p>So that the outcome is:</p>
<pre><code>.5555 | 1.33333
</code></pre>
<p>I've tried:</p>
<pre><code>df[['c1', 'c2']].div(d... | <p>Pretty straightforward, just divide by the values</p>
<pre><code>df[['c1', 'c2']]/df[['c3','c4']].values
</code></pre>
<p>Orders matter, so make sure to use correct ordering in the denominator. No need to recreate the DataFrame</p> | python|pandas|numpy|dataframe|operation | 3 |
369,351 | 53,316,470 | Upload numpy array as grayscale image to S3 bucket | <p>I have made some mathematical operations on some grayscaled images in python using numpy. </p>
<p>Now I want to upload the resulting numpy arrays as png images to my S3 bucket.
I have tried to upload them as base64 formats, but in that way I cannot open them as images from S3. My code looks as follows:</p>
<pre><... | <p>So I needed to convert the numpy array into an image first.
The following code turned out to work:</p>
<pre><code>from PIL import Image
import io
img = Image.fromarray(numpy_image).convert('RGB')
out_img = BytesIO()
img.save(out_img, format='png')
out_img.seek(0)
s3.Bucket('my-pocket').put_object(Key='cluster.pn... | python|numpy|amazon-s3|bucket | 6 |
369,352 | 53,296,165 | Keras: update model with a bigger training set | <p>I trained a model with Keras for text classification (supervised learning) using a training set. Let's say that there are 50.000 sentences in this training set.</p>
<p>During a week I collect 5.000 new sentences and I add them to the old training set.</p>
<p>If next week I want to train a new model with the new an... | <p>You can save/load model/weights. Check out this <a href="https://machinelearningmastery.com/save-load-keras-deep-learning-models/" rel="nofollow noreferrer">tutorial</a> by Jason Brownlee. <br></p>
<p>After you loaded the weights, you can start training with the new dataset (the 55000 samples). As the 'training' is... | python|tensorflow|keras | 1 |
369,353 | 53,010,186 | Convert row data into column data in pandas | <p>I have data that looks like this:
Field Value</p>
<pre><code>0 CRD 146099
1 LegalName CHUNG, BUCK CHWEE
2 BusName PRINCIPA FINANCIAL ADVISORS
3 URL https://adviserinfo.sec.gov/IAPD/content/ViewF...
4 CRD 170701
5 LegalName MESSINA AND ASSOCIATES, INC
6 BusName FINANCIAL RESOURCES GROUP
7 URL h... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> for 2 columns first, then create counter <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" r... | python|pandas | 1 |
369,354 | 52,953,874 | Python - Appending row number with reverse counter | <p>I have yet another Python question. This one probably can be achieved with help of a loop, however I was looking for a leaner solution</p>
<p>Suppose that I have a data frame like this one:</p>
<p><a href="https://i.stack.imgur.com/nLdOs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nLdOs.png"... | <h2>Setup:</h2>
<pre><code>df = pd.DataFrame([
pd.Series(pd.date_range('1/1/2018', '1/7/2018').append(pd.date_range('1/1/2018', '1/7/2018'))),
pd.Series(['Joe']*7 + ['Helen']*7),
pd.Series([1,1,0,0,0,0,1,0,1,1,0,1,0,0]),
]).T
df.columns = ['date', 'salesman', 'sold']
df['date'] = pd.to_datetime(df['date'])... | python|pandas|loops|numpy | 1 |
369,355 | 53,200,871 | df index to hour (can't use to.datetime) | <p>I want to add new column 'time' which are the convertion form index, e.g. 1 to 01:00, 2 to 02:00 (for <strong>hour</strong>). I tried to datetime but it resulted to full date and index only turns into second. </p>
<pre><code>df['time'] = df.index
prob time
0 9.172968e-01 0
1 8.585100e-01 ... | <p>Please check whether this works.</p>
<pre><code>df = df.assign(time = [ datetime.datetime.strptime(str(val),'%H').strftime('%H-%M') if val < 24 else datetime.datetime.strptime(str(val%24),'%H').strftime('%H-%M') for val in df.index.values])
</code></pre> | python|pandas|datetime|dataframe | 0 |
369,356 | 53,049,312 | Pandas package dealing with ugly column names | <p>I am trying to access some columns in a spreadsheet that has ugly column names (e.g. spaces, parens,...) using pandas in python. I have this code snippet:</p>
<pre><code>colnames= ['Name', 'Powered On', 'Connection State', 'Idle','Memory (GB)', 'Mem Recomm','Disk Recomm', 'Disk (GB)', 'ThinProvDisk', 'Max Read IO',... | <p>There are a few ways that you can extract a particular column(s) from your dataframe. To extract a single column, you can do either of the following:</p>
<pre><code>data['Powered On']
</code></pre>
<p>Or if there are no spaces or punctuation in your desired column name:</p>
<pre><code>data.Name
</code></pre>
<p>... | python|pandas | 1 |
369,357 | 53,286,961 | pandas apply custom func problem ('if' statement doesn't work) | <p>I made the func for apply as below:</p>
<pre><code>def NewMonth(x):
if x == 1 or 2:
return 1
elif x == 3 or 4:
return 2
elif x == 5:
return 3
elif x == 6:
return 4
elif x == 7 or 8:
return 5
elif x == 9 or 10:
return 6
elif x == 11 or 12:
... | <p>The other solutions solved your problem, but really for this type of calculation you should use <code>.map</code> or <code>pd.cut</code></p>
<h3>Sample Data:</h3>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'Month': np.random.randint(1,13,10)})
</code></pre>
<h3><code>.map</code></h3>
<p... | python|pandas|if-statement|lambda|apply | 2 |
369,358 | 53,209,042 | Change value of a column if within a time range | <p>I am trying to modify the values of one column if they fall between the following time (17:00 to 23:00), otherwise, they have to keep the same values. This is my code:</p>
<pre><code>lclstd['Response KWH/hh (per half hour) ']=lclstd['KWH/hh (per half hour) '].astype(float)
</code></pre>
<p>Extracting time from dat... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.time.html" rel="nofollow noreferrer"><code>pd.Series.dt.time</code></a> returns <a href="https://docs.python.org/3/library/datetime.html#datetime.time" rel="nofollow noreferrer"><code>datetime.time</code></a> objects. So you can perform... | python|pandas|datetime|dataframe|indexing | 0 |
369,359 | 53,329,891 | python or dask parallel generator? | <p>Is it possible in python (maybe using dask, maybe using multiprocessing) to 'emplace' generators on cores, and then, in parallel, step through the generators and process the results? </p>
<p>It needs to be generators in particular (or objects with <code>__iter__</code>); lists of all the yielded elements the genera... | <p>Dask's read_csv is designed to load data from multiple files in chunks, with a chunk-size that you can specify. When you operate on the resultant dataframe, you will be working chunk-wise, which is exactly the point of using Dask in the first place. There should be no need to use your iterator method.</p>
<p>The da... | python|pandas|python-multiprocessing|dask | 1 |
369,360 | 53,132,858 | My loop only saves the result of last iteration | <pre><code>import numpy as np
import pandas as pd
</code></pre>
<p>This is my data:</p>
<pre><code>ts = pd.DataFrame([0,1,2,3,4,5,6,7,8,9,10,11,12])
ts.columns = ["TS"]
start_df = pd.Series([1,3,6])
end_df = pd.Series([2,7,10])
</code></pre>
<p>I have created the following function to clean up my loop, and a for loo... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code></a> with list comprehension for list of boolean mask and then <code>sum</code> it for count <code>True</code> values (are processes like <code>1</code>), thanks @RafaelC for ... | python|pandas | 2 |
369,361 | 53,162,909 | removing duplicate values based on multiple conditions through pandas | <p>Dataframe looks like this</p>
<pre><code>APMC Commodity Year Month Price
1 A 2015 Jan 1232
1 A 2015 Jan 1654
2 A 2015 Jan 9897
2 A 2015 Feb 3467
2 B 2016 Jan 7878
2 B 2016 ... | <p>You can specify columns on which to detect duplicates:</p>
<pre><code>df.drop_duplicates(subset=['APMC', 'Year', 'Commodity', 'Month'],
inplace=True)
</code></pre>
<p>Result:</p>
<pre><code>>>> df
APMC Commodity Year Month Price
0 1 A 2015 Jan 1232
2 2 ... | python|pandas | 1 |
369,362 | 53,297,261 | Iteration over the rows of a Pandas DataFrame as dictionaries | <p>I need to iterate over a pandas dataframe in order to pass each row as argument of a function (actually, class constructor) with <code>**kwargs</code>. This means that each row should behave as a dictionary with keys the column names and values the corresponding ones for each row.</p>
<p>This works, but it performs... | <p>one clean option is this one:</p>
<pre class="lang-py prettyprint-override"><code>for row_dict in df.to_dict(orient="records"):
print(row_dict['column_name'])
</code></pre> | python|pandas|performance | 48 |
369,363 | 53,204,747 | Keras variable() memory leak | <p>I am new to Keras, and tensorflow in general, and have a problem. I am using some of the loss functions (binary_crossentropy and mean_squared_error mainly) to calculate the loss after prediction. Since Keras only accepts it's own variable type, I am creating one and supply it as an argument. This scenario is execute... | <p>I just removed the <code>with</code> statement (probably some tf code), and I don't see any leak. I believe there is a difference between the keras session and the tf default session. So you were not clearing the correct session with <code>K.clear_session()</code>. Probably using <code>tf.reset_default_graph()</code... | python|tensorflow|memory-leaks|keras | 1 |
369,364 | 53,255,172 | Convert JSON column in dataframe to simple array of values | <p>I am trying to convert the JSON in the bbox (bounding box) column into a simple array of values for a DL project in python in a Jupyter notebook.</p>
<p>The possible labels are the following categories: [glass, cardboard, trash, metal, paper].</p>
<pre><code>[{"left":191,"top":70,"width":183,"height":311,"label":"... | <p>You'll want to use a JSON decoder: <a href="https://docs.python.org/3/library/json.html" rel="nofollow noreferrer">https://docs.python.org/3/library/json.html</a></p>
<p></p>
<pre><code>import json
li = json.loads('''[{"left":191,"top":70,"width":183,"height":311,"label":"glass"}]''')
d = dictionary = li[0]
result... | python|json|pandas|jupyter-notebook | 1 |
369,365 | 52,969,157 | numpy.unique vs collections.Counter performance question | <p>I am trying to compute the number of occurrences of pairs of values. When running the following code the numpy version (pairs_frequency2) is more than 50% slower than the version relying on collections.Counter (it gets worse when the number of points increases). Could someone please explain the reason why.</p>
<p>I... | <p><code>numpy.unique</code> sorts its argument, so its time complexity is O(n*log(n)). It looks like the <code>Counter</code> class could be O(n).</p>
<p>If the values in your arrays are nonnegative integers that are not too big, this version is pretty fast:</p>
<pre><code>def pairs_frequency3(x, y, maxval=15):
... | python|numpy | 2 |
369,366 | 53,304,800 | Pandas read_excel() parses date columns with blank values to NaT | <p>I am trying to read an excel file that has date columns with the below code</p>
<pre><code>src1_df = pd.read_excel("src_file1.xlsx", keep_default_na = False)
</code></pre>
<p>Even though I have specified, keep_default_na = False, I see that the data frame has 'NaT' value(s) for corresponding blank cells in Excel d... | <pre><code>src1_df = pd.read_excel("src_file1.xlsx", na_filter=False)
</code></pre>
<p>Then you will have empty string ("") as "na" value</p>
<p>In my case I read excel per line and replace "" and "NaT" to None:</p>
<pre><code>for line in src1_df.values:
for index, value in enumerate(line):
if value == '... | python-3.x|pandas | 0 |
369,367 | 52,974,226 | Python Pandas compare date columns, check if not empty, conditional > <= logic, return value | <p>using Python3 Pandas, I'm trying to calculate RESULT. I keep getting Boolean ambiguous value errors. Do I need to test that each date column I compare with is not null first to avoid an error? The end result should mimic:</p>
<pre><code>#check if D3_UNTIL is not empty
if df.RUNNING_DATE.isna()==False:
if df.D3_... | <p>With if-else statements you can use <code>np.select</code> to implement your logic. Also checking <code>df.RUNNING_DATE.isna()==False</code> is superfluous; just use <code>df.RUNNING_DATE.notnull()</code>. </p>
<p>Further, the logic here can be simplified <strong>immensely</strong>. </p>
<ul>
<li>Any <code>>=</... | python|pandas | 2 |
369,368 | 65,624,626 | How to speed up rank function in pandas series? | <p>I want to roll over to calculate the rank of a series.</p>
<p>Assume I have a pandas series:</p>
<pre><code>In [18]: s = pd.Series(np.random.rand(10))
In [19]: s
Out[19]:
0 0.340396
1 0.664459
2 0.647212
3 0.529363
4 0.535349
5 0.781628
6 0.313549
7 0.933539
8 0.618337
9 0.013442
dtyp... | <p>It's faster with scipy/numpy (requires the <a href="https://github.com/numpy/numpy/releases/tag/v1.20.0rc2" rel="nofollow noreferrer">latest version of numpy</a>):</p>
<pre><code>import pandas as pd
import numpy as np
from time import time
from scipy.stats import rankdata
from numpy.lib.stride_tricks import sliding_... | python|pandas | 2 |
369,369 | 65,500,025 | Pandas Dataframe - trouble accessing a column with a numeric name | <p>I'm trying to clean up some dirty data. Each row is supposed to have a PhraseID, but for weird reasons, after massaging and merging several dataframes, I ended up with a column name of '2'.</p>
<p>But I'm having trouble getting the value of that field. If I try row['2'] I get a Python KeyError.
Are all rows not gu... | <p>The column name can be an int.</p>
<p>you could rename with:</p>
<pre class="lang-py prettyprint-override"><code>df_master_combined.rename(columns={2: 'PhraseId2'}, inplace=True)
</code></pre> | python-3.x|pandas|dataframe | 1 |
369,370 | 65,768,729 | How to change data augmentation parameters dynamically in the config file of Tensorflow Object Detection pipelines? | <p>I am trying to create an object detection framework which takes input from user and creates custom object detection models based on the user selection.
For this I have to dynamically make some changes in the config files based on the model ,the hyperparameters and the augmentation options selected by the user.
So fa... | <p>Below is a guess that I posted on <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/protos/preprocessor.proto" rel="nofollow noreferrer">this page</a> because I accidentally confused it with this page:</p>
<hr />
<p>I'm very new to programming but I wanted to share something that I ... | python|tensorflow|protocol-buffers|config|object-detection-api | 0 |
369,371 | 65,823,749 | Saving a list of AWS S3 bucket content and downloading filtered content of list | <p>I have this problem that I am trying to solve, but I cannot find an answer. The problem is actually 2-fold. The first part related to listing all the files in an s3 bucket in AWS. The second part is to download the files that I choose from that list.</p>
<p><b>Part 1: Listing all the files</b></p>
<p>So, I know how ... | <p>A few things to note:</p>
<ul>
<li>There is no need to reference AWS credentials within your code files. Instead, use the AWS CLI <code>aws configure</code> command to store the credentials in a configuration file. Boto will then automatically find and use them.</li>
<li>In your Part 1 second code block, it is refer... | python|pandas|amazon-web-services|boto3 | 2 |
369,372 | 65,741,729 | Keras model compilation settings (view/change) | <p>Suppose I have the following Keras model:</p>
<pre><code>model = Sequential()
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
model.compile(
loss = CategoricalCrossentropy(label_smoothing=0.01),
optimizer = RMSprop(learning_rate=0.001, momentum=0.0)
metric... | <p>Use <code>.lr</code>:</p>
<pre><code>rate = model.optimizer.lr
</code></pre> | tensorflow|keras | 1 |
369,373 | 65,643,135 | Get string instead of list in Pandas DataFrame | <p>I have a column <code>Name</code> of string data type. I want to get all the values except the last one and put it in a new column <code>FName</code>, which I could achieve</p>
<pre><code>df = pd.DataFrame({'Name': ['John A Sether', 'Robert D Junior', 'Jonny S Rab'],
'Age':[32, 34, 36]})
df[... | <p>You can use <code>.str.rsplit</code>:</p>
<pre><code>df['FName'] = df['Name'].str.rsplit(n=1).str[0]
</code></pre>
<p>Or you can use <code>.str.extract</code>:</p>
<pre><code>df['FName'] = df['Name'].str.extract(r'(\S+\s?\S*)', expand=False)
</code></pre>
<p>Or, you can chain <code>.str.join</code> after <code>.str.... | python|pandas|dataframe | 4 |
369,374 | 65,696,968 | How to i get word embeddings for out of vocabulary words using a transformer model? | <p>When i tried to get word embeddings of a sentence using bio_clinical bert, for a sentence of 8 words i am getting 11 token ids(+start and end) because "embeddings" is an out of vocabulary word/token, that is being split into <code>em</code>, <code>bed</code> ,<code>ding</code>, <code>s</code>.</p>
<p>I wou... | <p>To my knowledge, mean aggregation is the most commonly used tool here, and in fact there is even scientific literature, empirically showing that it works well:
<a href="https://www.aclweb.org/anthology/D18-1059.pdf" rel="nofollow noreferrer">Generalizing Word Embeddings using Bag of Subwords</a> by Zhao, Mudgal and ... | nlp|huggingface-transformers|transformer-model|huggingface-tokenizers | 2 |
369,375 | 65,752,892 | Keras LSTM predict with sequence | <p>I made a Keras LSTM Model. But my problem is that with my input_shape [800, 200, 48] i predict a output with the shape [800, 200, 48].</p>
<p>I only need to predict the 800x48 labels without any sequences.</p>
<p><a href="https://i.stack.imgur.com/I4BqL.png" rel="nofollow noreferrer">enter image description here</a>... | <p>For this, the parameter <code>return_sequences</code> of your last <code>LSTM</code> layer should be <code>False</code>. Since you're using a loop, try something like this. Here, <code>return_sequences</code> will be <code>True</code> for all except the last loop iteration.</p>
<pre><code>import tensorflow as tf
mo... | python|tensorflow|keras|lstm|tensorflow2.0 | 0 |
369,376 | 65,516,535 | How to add rows for a timeseries dataframe? | <p>I am writing a program that will load in a timeseries excel file into a dataframe, then I create several new columns using some basic calculations. My program is going to sometimes read in excel files that are missing months for some records. So in example below I have monthly sales data for two different stores. Th... | <ol>
<li>just try <code>upsample</code> of the DateTime index. ref: <a href="https://stackoverflow.com/questions/51790793/pandas-resample-upsample-last-date-edge-of-data">pandas-resample-upsample-last-date-edge-of-data</a></li>
</ol>
<pre><code># group by `Store`
# with `Month End Date` column show be converted to Date... | python|pandas|dataframe | 0 |
369,377 | 65,497,283 | How to build a model having multiple inputs and a single output using Keras | <p>I am trying to use the functional api of Keras to build a model having multiple inputs and a single output.
The goal is to combine each row of each input to predict the corresponding output (either 1 or 0).<br />
for example <code>concatenate(inputs_1[0], and inputs_2[0])</code> and predict output <code>outputs[0]</... | <p>There are a ton of questions you are asking which is usually not inline with <a href="https://stackoverflow.com/help/how-to-ask">SO guidelines</a>. It would be better to tackle (search first, ask later if not found) each question separately.</p>
<p>Still, just to help you get started, I'll try to answer them in orde... | python|tensorflow|keras|jupyter-lab|functional-api | 2 |
369,378 | 65,516,526 | Can you use a different image size during transfer learning? | <p>I have made a switch from TensorFlow to PyTorch recently. I use a famous <a href="https://github.com/rwightman/gen-efficientnet-pytorch/tree/master/geffnet" rel="nofollow noreferrer">Github repo</a> for training on <code>EfficientNets</code>. I wrote the model initiation class as follows:</p>
<pre class="lang-py pre... | <p>Yes you can use different input sizes when it comes to transfer learning, after all the model that you load is just the set of weights of the fixed sequence of layers and fixed convolution kernel sizes. But I believe that there is some sort of minimum size that the model needs to work efficiently. You would still ne... | machine-learning|deep-learning|neural-network|pytorch|transfer-learning | 1 |
369,379 | 65,692,540 | Create a boolean column if one of the columns is greater than 0 | <p>I have a dataframe and I want to set up two conditions</p>
<p>I want to return all columns with col1 == 0 and col7 == True</p>
<pre><code> col1 col2 col3 col4 col5 col6 col7
0 0.0 0.0 0.0 0.0 0.0 False True
1 0.0 0.0 4.0 0.0 0.0 True False
2 0.0 2.0 0.0 0.0 0.0 False True
</code></pre>
<p>I wrote thi... | <p>Use <code>.any()</code>:</p>
<pre><code>code = ['col2', 'col3', 'col4']
df['bool_col'] = df[code].gt(0).any(1)
</code></pre> | python|pandas | 1 |
369,380 | 65,736,983 | Problem in elemintaing the brackets () and post processing the dataframe using Pandas in Python | <p>I am just a beginner in the Python so kindly excuse for this question, I tried a lot to get it done, but failed, thus I am posting this. I have a data set which looks like:</p>
<pre><code> 5.96303e-07 (11.6667 3.21427 -2.20471e-07) (11.8746 -1.75419 -2.37923e-07) (8.66991 -2.8487... | <p>There are two relatively minor issues. Something like the following might be what you're looking for. Maybe.</p>
<p>First, the column you are trying to plot is a string. Essentially it contains letters/symbols. Even when you remove the "(" ")" the "numbers" are still considered a strin... | python|pandas|dataframe|matplotlib | 4 |
369,381 | 65,909,373 | How can I concatenate date from another column when I use groupby and aggregation in a pandas dataframe | <p>I am having the following dataframe initially, then I perform a groupby and an aggregate to concatenate overlapping time ranges. I want to add another column in the final dataframe and this column will be formed by a concatenation of data on the overlapping rows.</p>
<pre><code>df['newid']=(df['START']-df['END'].shi... | <p>You can aggregate the method <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow noreferrer"><code>str.join</code></a>:</p>
<pre><code>(df.groupby(['newid','ELEMENT'])
.agg({'START': 'min', 'END':'max', 'TEXT': ' ; '.join})
.reset_index(1))
</code></pre>
<p><strong>Output</strong... | python|pandas|dataframe | 0 |
369,382 | 65,550,028 | Count the number of specific values in multiple columns pandas | <p>I have a data frame:</p>
<pre><code>A B C D E
12 4.5 6.1 BUY NaN
12 BUY BUY 5.6 NaN
BUY 4.5 6.1 BUY NaN
12 4.5 6.1 0 NaN
</code></pre>
<p>I want to count the number of times 'BUY' appears in each row. Intended result:</p>
<pre><code>A B C D E score
12 4.5 6.1 B... | <p>You can compare and then sum:</p>
<pre><code>df['score'] = (df[['B','C','D','E']] == 'BUY').sum(axis=1)
</code></pre>
<p>This sums up all the booleans and you get the correct result.</p>
<hr />
<p>When you do <code>df[df == 'BUY']</code>, you are just replacing anything which is not <code>BUY</code> with <code>np.na... | python|pandas|dataframe | 6 |
369,383 | 65,576,442 | Trying to understand pandas.DataFrame.mode() output shape | <p>I need to compute the mode along the rows of specific columns of a pandas DataFrame.</p>
<p>I have no problems in following the on-line examples. The following code works fine:</p>
<pre><code>import numpy as np
import pandas as pd
import platform
import sys
print('python', platform.python_version())
print('nump... | <p>Reason is because there are same number of maximal number of values, so pandas return all modes.</p>
<pre><code>#chnaged data
data = [[np.nan, np.nan, np.nan, np.nan, np.nan],
[1, 1, 0, 0, -1],
[1, -1, np.nan, 1, -1],
[-1, np.nan, 1, np.nan, -1]]
df = pd.DataFrame(data, columns=['a1', 'a2'... | python|pandas | 0 |
369,384 | 65,530,768 | joining string for a counter in python dataframe | <p>I have read a <code>csv</code> which has two columns: <code>date</code>, and <code>tweet</code>. The file is read in a <code>df</code>,</p>
<pre><code>
df= pd.read_csv(
"data/101.csv",
usecols=["date", "tweet"]
.rename(
columns={
"date": "date"... | <pre><code>I also tried:
count=3
for c in count:
for t in df['tweet']:
df['combined_tweets'] += str(t)
print(df['combined_tweets'])
And this time I got:
TypeError: 'int' object is not iterable
</code></pre>
<p>Here you can't do a for loop straigth from an integer, you need to use <code>range</code> function to ... | python|string|dataframe|join|pandas-groupby | 0 |
369,385 | 65,504,651 | Replace the values of multiple rows with the values of another row based on a condition in Pandas | <p><a href="https://i.stack.imgur.com/iKHsA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iKHsA.png" alt="Table description" /></a></p>
<p>I want to replace the values of the columns A, B, C, D with the values where region = '' for the a unique value for the year 2011. For example, the unique colum... | <p>I think you need this:</p>
<pre><code>df=df.groupby(['unique','year']).agg('last').reset_index()
</code></pre> | python|pandas|dataframe|data-manipulation | 1 |
369,386 | 65,809,906 | TypeError: Could not build a TypeSpec for <KerasTensor when using tf.map_fn and keras functional model | <p>When I attempt to use tf.map_fn in the definition of a keras Functional model, I get the error:</p>
<pre><code>TypeError: Could not build a TypeSpec for <KerasTensor: ...
</code></pre>
<p>e.g. this simple model will trigger that error in tf-nightly 2.5.0 :</p>
<pre><code>import tensorflow as tf
from tensorflow.k... | <p>This seems to result from tf.map_fn being unable to determine the TypeSpec of the input tensor when the input is a keras sympolic Input.</p>
<p>Several times now I've run into problems with tensorflow ops and Keras symbolic Input tensors. Wrapping the offending code in a custom layer seems to generally fix it.</p>
<... | python|tensorflow|keras | 2 |
369,387 | 65,599,414 | How to prepare targets for Sparse categorical entropy | <p>I want to performing multiclass semantic segmentation. My images are grayscale.</p>
<pre><code>image:(256,256,1)
</code></pre>
<p>I tried one hot encoding for multiclass segmentation and it works. The shape of my mask or target looks like this after one hot encoding. I have 8 classes.</p>
<pre><code>mask:(256,256,8)... | <p>If your target one-hot vectors were: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], then they should be [0, 1, 2] to use sparse cross entropy.</p>
<p>If your target shape was (256, 256, 8) then its shape should be (256, 256).</p>
<p>I would advice to run <code>model.summary()</code> to see the shapes.</p> | python|tensorflow|neural-network|mask|loss-function | 1 |
369,388 | 65,643,401 | How to subset rows based on date overlap range efficiently using python pandas? | <p>My data frame has two date type columns: start and end (yyyy-mm-dd).</p>
<p>Here's my data frame:</p>
<pre><code>import pandas as pd
import datetime
data=[["2016-10-17","2017-03-08"],["2014-08-17","2016-09-08"],["2014-01-01","2015-01-01"],["2017-12-2... | <p>A trick I learned early on in my career is what I call "crossing the dates": you compare the start of one range against the end of the other.</p>
<pre class="lang-py prettyprint-override"><code># pd.Timestamp can do everything that datetime/date does and some more
ref_start = pd.Timestamp(2015, 9, 20)
ref_... | python|pandas|date | 2 |
369,389 | 65,668,572 | Plot category, proportion, total | <p>I am trying to make bar plot in python using name, prop, total. The idea is I should have name and then if I can show total streams and what proportion are male.</p>
<p>I have following example data</p>
<pre><code>NAME prop_male total
GGD 0.254147 727240
CCG 0.216658 323510
PPT 0.265414 2... | <p>Various ways to achieve this. One would be to calculate the number of males and plot the bars ontop of each other:</p>
<pre><code>import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
df = pd.DataFrame({"name": list("ABC"), "proportion": [0.2, 0.7, 0.1], "... | python|pandas|matplotlib|seaborn|percentage | 2 |
369,390 | 65,906,610 | Function to subtract each element in a list | <p>I’m attempting to make a function to subtract each element from a list in python, however, the first element must be <code>nan</code>.</p>
<p>This is my function:</p>
<pre><code>def sub_vector(x):
from numpy import nan
y=[]
for j, i in enumerate(range(len(x)-1)):
z= np.nan
if j == 0:
y... | <pre><code>from numpy import nan
def sub_vector(x):
return [nan] + [x[i] - x[i - 1] for i in range(1, len(x))]
</code></pre> | python|numpy|func | 1 |
369,391 | 65,774,160 | ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() for a for loop | <pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': '... | <p>You can change remove <code>False</code> output in loop:</p>
<pre><code>for i in range(len(df.index)):
if df['links'].str.contains('https')==False:
df.drop()
</code></pre>
<p>to filter only rows with match condition in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolea... | python|pandas|dataframe | 2 |
369,392 | 65,848,040 | Store 3d-array in a pandas dataframe column | <p>I'd like to store a 3D-numpy array in a column of a dataframe.</p>
<pre><code>df = pd.DataFrame({"nodes": list(range(1, 4))})
df = df.set_index("nodes")
df[0] = list(range(1, 6, 2))
df[1] = [10,20,30]
>>> df
0 1
nodes
1 1 10
2 3 ... | <p>Use this:</p>
<pre><code>df[2] = test.tolist()
</code></pre>
<p>output:</p>
<pre><code> 0 1 2
nodes
1 1 10 [[1, 2, 3], [4, 5, 6]]
2 3 20 [[10, 20, 30], [40, 50, 60]]
3 5 30 [[0, 1, 0], [-1, -1, -1]]
</code></pre> | python|pandas|numpy | 1 |
369,393 | 65,824,569 | Can't apply gradients on tf.Variable | <p>I am trying to learn a similarity matrix(M) between two image embeddings, A single instance of training is a pair of images - (anchor, positive). So ideally the model will return 0 distance for embeddings of similar images.</p>
<p>The problem is, when i declare the distance matrix(M) as a tf.Variable, it returns an ... | <p>The python <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer"><code>zip</code></a> function expects iterable objects, like for example a list or a tuple.</p>
<p>In your calls to <code>tape.gradient</code>, or <code>optimizer.apply_gradients</code>, you can put your Variable in a... | tensorflow|machine-learning|keras|deep-learning | 1 |
369,394 | 65,731,556 | Unable to read a column of an excel by Column Name using Pandas | <p><a href="https://i.stack.imgur.com/QiiOA.png" rel="nofollow noreferrer">Excel Sheet</a></p>
<p>I want to read values of the column 'Site Name' but in this sheet, the location of this tab is not fixed.
I tried,</p>
<pre><code>df = pd.read_excel('TestFile.xlsx', sheet_name='List of problematic Sites', usecols=['Site N... | <p>You can first check dataframe without mentioning column name while reading excel file.
Then try to read column names.</p>
<p>Code is as below</p>
<pre><code>import pandas as pd
df = pd.read_excel('TestFile.xlsx', sheet_name='List of problematic Sites')
print(df.head)
print(df.columns)
</code></pre> | python|python-3.x|excel|pandas|dataframe | 0 |
369,395 | 65,569,919 | Using pandas.pct_change() on dataset results in 'nan' loss in tensorflow model | <p>Let's say I have a dataframe like so:</p>
<pre><code>df = pd.DataFrame({'Inputs': np.arange(100), 'Labels': np.multiply(np.arange(100),5)})
df.head()
</code></pre>
<pre><code> Inputs Labels
0 0 0
1 1 5
2 2 10
3 3 15
4 4 20
</code></pre>
<p>For simplicity, let <code>model</code> be just one Dense ... | <p>Figured out the answer on my own. Stupidly, the example code I wrote out above is exactly the issue, haha.</p>
<p>Indeed, the model will train fine on the actual data, and indeed the model will not train fine on any data that has NaN or inf values in it.</p>
<p>But if you try to train on data with NaN or inf values,... | python|pandas|dataframe|numpy|tensorflow | 0 |
369,396 | 65,746,739 | multiple levels of pivot_table with pandas | <p>I am trying to do multiple rounds of pivot_table to turn my flat data into something I can use for a project.</p>
<p>Here is some sample data organized similarly to how it's coming out of the database.</p>
<pre><code>df = pd.DataFrame(
[[123456, 'Student A', 'Algebra I', 9, 'S1', 'A'],
[123456, 'Student A', ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer">sort_index</a> to sort the indices based on <code>level</code>. Level 0 in this case is slightly tricky. So, I projected it before sorting the indices; <code>[['course_name', 'S... | python|pandas|dataframe | 1 |
369,397 | 65,485,750 | Find unique tuples in 3D numpy array | <p>I am trying to find uniques tuples within a numpy array but am unable to. Based on other SO answer I tried <code>np.unique</code> while setting the value for the axis, but it's not providing me what I'm looking for. Here's an example:</p>
<p>I have the following array</p>
<pre><code>b = np.array([[[255, 0, 0], [255,... | <p>Make b into a Nx3 array first. Then use unique.</p>
<pre><code>>>> np.unique(b.reshape(-1, 3), axis=0)
array([[ 0, 0, 0],
[255, 0, 0]])
</code></pre> | python|numpy | 3 |
369,398 | 65,522,954 | Using generator to create a masking function for a dataframe | <p>I have a lengthy dataframe comprised of 5 indicator variables. Each row will sum to 3 (i.e. 3 indicated characteristics will be present). I would like to iterate through the dataframe and mask n variables (i.e. 1 or 2 indicators get flipped from 1 to 0) at random for all rows.</p>
<p>If my input table is structure... | <p>Generators can help you to keep memory use low, by not materializing lists, but instead only yielding one element at a time. However, they'll do nothing for performance, and working essentially like a normal for-loop (or even slower, since each new element is effectively a function call).</p>
<p>If you want performa... | python|numpy|generator | 1 |
369,399 | 65,543,013 | How can I add a calculated column with different rows to a dataframe? | <p>I am getting some data on some websites with dataframe.
There is a column that name is "Open" it shows me open prices.
I am adding a new column to my frame which name is <strong>Calculation</strong>.
I am trying to make a calculation for today's open prices with yesterday's open prices.</p>
<p>How can I ge... | <p>You're looking for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>df['Open'] - df['Open'].shift()
</code></pre> | python|pandas|dataframe | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.