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
19,900
46,204,241
How to remove microseconds from timedelta
<p>I have microseconds that I want to essentially truncate from a pandas column. I tried something like <code>analyze_me['how_long_it_took_to_order'] = analyze_me['how_long_it_took_to_order'].apply(lambda x: x.replace(microsecond=0)</code> but to this error came up <code>replace() takes no keyword arguments</code>.</p...
<p>I think you need to convert your string in to a timedelta with <code>pd.to_timedelta</code> and then take advantage of the excellent dt accessor with the floor method which truncates based on string. Here are the first two rows of your data.</p> <pre><code>df['how_long_it_took_to_order'] = pd.to_timedelta(df['how_l...
python|pandas|timedelta
4
19,901
58,428,363
Pre Process the dataset
<p>I have a dataset df with the following entries.. </p> <pre><code>Date Count 19/09/2019 1491 20/09/2019 1692 21/09/2019 1753 22/09/2019 1817 23/09/2019 1986 24/09/2019 2022 25/09/2019 2343 26/09/2019 2277 27/09/2019 2343 28/09/2019 2599 29/09/2019 2622 30/09/2019 2704 01/10/2019 290...
<p>Your first step is create <code>TimeSeries</code>, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="no...
python|pandas
0
19,902
69,079,721
Pandas: New_Column = Column_A - Column_B, values in New_Column are the values of the first cell of New_Column. need fix
<p>I've come across an issue with pandas subtraction that confuses me. I am trying to do subtraction of one column with another. My data that is used are the residuals of arch_model, and ARIMAresult.</p> <p><a href="https://i.stack.imgur.com/3TsG7.png" rel="nofollow noreferrer">Data as follows</a></p> <p>Heres the issu...
<p>Looking at your picture you posted I think the problem might be coming from iterating through the data. Typically when subtracting one column from another you can just subtract the whole column at once and pandas will know your doing vector subtraction.</p> <pre><code>residuals['fitted_garch'] = residuals['arma_resi...
python|pandas|series|arima|arch
0
19,903
69,191,769
Complex indexing of a multidimensional array with indices of lower dimensional arrays in Python
<p><strong>Problem:</strong></p> <ul> <li><p>I have a numpy array of 4 dimensions:</p> <pre class="lang-py prettyprint-override"><code>x = np.arange(1000).reshape(5, 10, 10, 2 ) </code></pre> <p>If we print it:</p> <p><a href="https://i.stack.imgur.com/MzNrr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgu...
<p>Ah, I think I now get what you are after. Fancy indexing is <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">documented here</a> in detail. Be warned though that - in its full generality - this is quite heavy stuff. In a nutshell, fancy indexing allows...
python|numpy|multidimensional-array|indexing|numpy-slicing
2
19,904
44,642,649
Change dtype of ndarray from object to float?
<p>I found a strange 3D ndarray(see attached file) that does not show the shape of the last dimension and dtype change(asarray nor astype from 'object' to np.float) does not work.</p> <p><a href="https://drive.google.com/open?id=0BzxiDcBmvq-INGxuSDlwS295WW8" rel="nofollow noreferrer">file</a></p> <p>It is an ndarray ...
<p>With your download, I can load the array:</p> <pre><code>In [850]: data =np.load('../Downloads/strange_array.npy',encoding='latin1') In [851]: data.shape Out[851]: (2, 3) </code></pre> <p>the elements are all the same shape and dtype, so they can be joined into a 3d array:</p> <pre><code>In [852]: [i.shape for i ...
python|numpy|multidimensional-array|tuples|itertools
2
19,905
44,491,067
How to loop over all but last column in pandas dataframe + indexing?
<p>Let's day I have a pandas dataframe <code>df</code> where the column names are the corresponding indices, so 1, 2, 3,....len(df.columns). How do I loop through all but the last column, so one before len(df.columns). My goal is to ultimately compare the corresponding element in each row for each of the columns with t...
<p>To iterate over each column, use</p> <pre><code>for column_name, column_series in df.iteritems(): pass </code></pre> <p>To iterate over all but last column</p> <pre><code>for column_name, column_series in df.iloc[:, :-1].iteritems(): pass </code></pre> <hr> <p>I'd highly recommend asking another quest...
python|pandas|dataframe|indexing
7
19,906
60,996,871
how to pass a dataframe into string and call function from it?
<p>i'm passing a function who needs a dataframe to execute it, inside a variable string, and using the eval metric i'm trying to execute the function. But the code isn't working because the dataframe becames a string and it fails to understend it.</p> <p>What i'm doing is:</p> <pre><code>def function(dataframe, numbe...
<p>You can just call the function and it will work:</p> <pre><code>from IPython.display import display, HTML import pandas def function(dataframe, number1, number2): display(HTML(dataframe.to_html())) print(number1+number2) dataframe = pandas.DataFrame() number1 = 1 number2 = 1 a = f'function(dataframe, numb...
python|pandas|dataframe
0
19,907
60,967,132
Numpy - Use values as index of another arrays
<p>I face a problem with Numpy, I try to use the values of each row (of B) as the indexes of another multidimensional array (A):</p> <pre><code>&gt;&gt;&gt; A array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) &gt;&gt;&gt; B array([[ 0, 1, 2, 3], [ 1, 5, 6, 7], [ 8, 9, 10, 11]]) &g...
<p>It seems that you are looking for <code>np.take_along_axis</code>:</p> <pre><code>A = np.array([ [0, 1, 2], [3, 4, 5], [6, 7, 8]] ) B = np.array([ [ 0, 1, 2, 3], [ 1, 5, 6, 7], [ 8, 9, 10, 11]] ) C = np.clip(B, 0, 2) res = np.take_along_axis(A, C, 1) pri...
python|python-3.x|numpy|multidimensional-array|indexing
3
19,908
60,946,337
how to use str.replace in a lambda function in Pandas?
<p>I want to use <code>str.replace()</code>, inside a lambda function. But I am confused, where do I pass my lambda function's parameter, while using <code>str.replace()</code>, below are the details</p> <p>Input:</p> <pre><code>name_1 john&amp;&amp; mary&amp;&amp; tim&amp;&amp; </code></pre> <p>Expected Output:</p...
<p>As others mentioned in the comments, you can simply use str.replace</p> <pre><code>df1['new_name'] = df1['name_1'].str.replace('&amp;&amp;','') </code></pre> <p>OR</p> <pre><code>df1['new_name'] = df1['name_1'].apply(lambda a: str(a).replace('&amp;&amp;','')) </code></pre> <p>If you insist having lambda function...
python|pandas
3
19,909
60,880,713
Python Pandas : Find nth largest and count in case of tie
<p>In a pandas <code>DataFrame</code>, I want to find the nth largest value (row wise, not column wise) and then also find, if there are ties. I am interested in finding top 3 largest and ties. Note, there are more than 3 columns in actual problem, e.g. if the data frame looks like this:</p> <pre><code> A B C 0 1...
<pre class="lang-py prettyprint-override"><code>for i in range(len(df)): l = df.loc[0].tolist() d = {key: l.count(key) for key in l} </code></pre> <p>The dictionary now contains the values and how many times it has been repeated in the row. You can then print the top-n values of the dictionary easily.</p>
python|python-3.x|pandas
0
19,910
42,154,606
python numpy: how to construct a big diagonal array(matrix) from two small array
<pre><code>import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) C = np.array([[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 5, 6], [0, 0, 7, 8]]) </code></pre> <p>I would like to make <code>C</code> directly from <code>A</co...
<p><strong>Approach #1 :</strong> One easy way would be with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html" rel="noreferrer"><code>np.bmat</code></a> -</p> <pre><code>Z = np.zeros((2,2),dtype=int) # Create off-diagonal zeros array out = np.asarray(np.bmat([[A, Z], [Z, B]])) </code></pre...
python|arrays|numpy
14
19,911
42,582,405
Choosing a line delimiter in Pandas
<p>I have a data-set that has '^A' as the column delimiter and '^B' as the line delimiter. Currently when I try to read this in, everything is read in as a new column header because pandas is not recognizing that there is an end to the first line. I am just using a simple pandas read_csv statement. Here it is;</p> <pr...
<pre><code>df = pd.read_csv(StringIO("""h1^Ah2^Ah3^B111^A222^A333^B111^A222^A333^B111^A222^A333"""), sep='\^B',engine='python', header=None) df = df.stack().to_frame() df Out[52]: 0 0 0 h1^Ah2^Ah3 1 111^A222^A333 2 111^A222^A333 3 111^A222^A333 df = df[0].str.split('\^A', ...
python|pandas
-1
19,912
69,871,476
torch.nn.Sequential of designed blocks problem in giving inputs
<p>I have designed a class that is a block of a network and its forward has three inputs: x, logdet, reverse, and has two outputs. for example, everything is normal when I call this class and use it, like:</p> <pre><code>x = torch.Tensor(np.random.rand(2, 48, 8, 8)) net = Block(inp = 48, oup = 48, mid_channels=48, ksiz...
<p>You indicated that your <code>Block</code> <code>nn.Module</code> had a <code>reverse</code> option. However nn.Sequential doesn't, so <code>conv1_network(x, reverse=False)</code> is not valid because <code>conv1_network</code> is not a <code>Block</code>.</p> <p>By default, you can't pass <code>kwargs</code> to lay...
python|deep-learning|neural-network|pytorch|sequential
1
19,913
69,972,888
Timedelta without Date
<p>I have a column with times that are not timestamps and would like to know the timedelta to 00:30:00 o'clock. However, I can only find methods for timestamps.</p> <pre><code>df['Time'] = ['22:30:00', '23:30:00', '00:15:00'] </code></pre> <p>The intended result should look something like this:</p> <pre><code>df['Outpu...
<p>One could want to use <code>datetime.time</code> as data structures, but these cannot be subtracted, so you can't conveniently get a <code>timedelta</code> from them.</p> <p>On the other hand, <code>datetime.datetime</code> objects can be subtracted, so if you're always interested in positive deltas, you could const...
python|pandas|timedelta
1
19,914
43,151,289
How to reverse a NumPy array in-place?
<p>Is there any efficient way to reverse a NumPy <strong>in-place</strong>?</p> <h3>Note: I am <strong>NOT</strong> looking for a reversed <em>view</em>. I want the array to be truly reversed.</h3>
<p>It's inelegant, but if in-place is the most important factor and runtime is not as important (as numpy slicing will far out-perform the iterative approach), you could always swap indices from the left and right ends of the array until the indices converge:</p> <pre><code>def reverse(arr): ln = arr.shape[0] ...
python|arrays|numpy|reverse
0
19,915
72,258,190
filter data and replace values in pandas
<p>I am new to pandas and I am trying to replace some values on specific columns of a dataframe. My dataframe looks like this:</p> <pre><code> c1 c2 st mt ast sr c7 c8 0 a a 2 1 4 2 a a 1 b b 3 3 3 3 b b 2 c c 1 1 2 4 c c 3 d d 3 3 1 2 d d 4 e ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> with columnsnames in list:</p> <pre><code>df.loc[(df.st == 5) &amp; (df.mt == 5) &amp; (df.ast == 5) &amp; (df.sr == 5), ['st','mt','ast','sr']]=0 </code></pre> <...
python|pandas|dataframe|replace
1
19,916
72,323,594
Selecting certain indices from numpy array and adding 2
<pre><code>import numpy as np arr = np.array([1,2,3,4,5,6,7,8,9]) </code></pre> <p>How to add 2 to arr[0:2] and arr[5:6] so the final result is:</p> <pre><code>arr[3,4,3,4,5,8,7,8,9] </code></pre>
<p>Note that you could create an array that has all the indices to the values that need to be modified:</p> <pre><code>arr[np.r_[0:2, 5:6]] += 2 print(arr) </code></pre> <hr /> <p>Out:</p> <pre><code>array([3, 4, 3, 4, 5, 8, 7, 8, 9]) </code></pre>
python|arrays|numpy
2
19,917
72,399,515
How do I get the top 5 value from groupby and value_counts?
<p>I have a <a href="https://docs.google.com/spreadsheets/d/15_klD4NWgVNmji-UUAYZWivDvxcG58qjV1Q5h3oV52k/edit?usp=sharing" rel="nofollow noreferrer">dataset</a> (let's call it df) that looks like this:</p> <p><a href="https://i.stack.imgur.com/PNccC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNc...
<p>In your case try <code>head</code></p> <pre><code>out = df.groupby(['Source_Type'])['Source_Nationality'].value_counts(normalize=True)*100 out = out.sort_values(ascending=False).groupby(level=0).head(3) </code></pre>
python|pandas|group-by|pandas-groupby
0
19,918
72,366,989
How do I read and label images stored in two different directories for binary classification?
<p>The two directories I have contain many images, each image having a unique name. One directory is healthy, and another one is unhealthy.</p> <p>I need to read images from both the directories, and label the images from one directory as 1, and 0 from another directory, then create a numpy array with each each image m...
<p>Use <code>glob.glob(/path/to/directory/**.&lt;extension&gt;)</code> to get a list of images in a directory. You might need to use more than one call if there are multiple file extensions.</p> <p>Once you have a list of images, you can do</p> <pre><code>np.concatenate(np.array([images]), np.ones((1, len(images)))) </...
python|numpy|tensorflow|conv-neural-network
1
19,919
72,276,743
Apply function to every element in a list in a df column
<p>How do I apply a function to every element in a list in every row of a dataframe?</p> <p>df:</p> <pre><code>label top_topics adverts ['werbung', 'geschenke'] </code></pre> <p>my function looks something like this:</p> <pre><code>from langdetect import detect from googletrans import Translator def d...
<p>First, <a href="https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except">you should never use a bare <code>except</code></a>.</p> <p>Second, because your function translates a single word and returns the translated word and the detected language as a tuple, it would be difficult and tedio...
python|pandas|dataframe|apply
1
19,920
72,434,166
Generate a matrix of transition probabilities for bit strings of given size following some probability distribution
<p>I want to create an 8x8 matrix which provides the error probabilities in bit communication. The matrix looks as follows:<a href="https://i.stack.imgur.com/J5Dcn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J5Dcn.png" alt="enter image description here" /></a></p> <p>The columns amount to the observed qua...
<p>It turns out you can do this simply without <code>numpy</code> or <code>scipy</code>. I use <code>pandas</code> for nice printing.</p> <p>The logic is that for each bit, you have a probability of flipping (<code>p01</code> or <code>p10</code>) or remaining the same (<code>p00</code> or <code>p11</code>). Transformin...
python|numpy|probability|distribution
3
19,921
50,342,581
Can kernels other than periodic be used in SGPR in gpflow
<p>I am pretty new to <strong>GPR</strong>. I will appreciate it if you provide me some suggestion regarding the following questions:</p> <p>Can we use the <strong>Matern52</strong> kernel in a sparse Gaussian process?</p> <p>What is the best way to select pseudo inputs (Z) ? Is random sampling reasonable?</p> <p>I ...
<p>Have you tried it out on a small test set of data, that you could perhaps post here? There is no reason Matern52 shouldn't work. Randomly sampling inducing points should be a reasonable initialisation, especially in higher dimensions. However, you may run into issues if you end up with some inducing points very clos...
python-3.x|tensorflow|machine-learning|gaussian|gpflow
1
19,922
50,277,199
Numpy compare array to multiple scalars at once
<p>Suppose I have an array</p> <pre><code>a = np.array([1,2,3]) </code></pre> <p>and I want to compare it to some scalar; this works fine like</p> <pre><code>a == 2 # [False, True, False] </code></pre> <p>Is there a way I can do such a comparison but with multiple scalars at once? The default behavior when comparin...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html" rel="noreferrer">Outer product, except it's equality instead of product</a>:</p> <pre><code>numpy.equal.outer(scalars, a) </code></pre> <p>or adjust the dimensions and perform a <a href="https://docs.scipy.org/doc/numpy/user/basi...
python|numpy
5
19,923
50,651,691
Python running SQL query With WHERE IN {list} and list is too long
<p>Here is a part of my script :</p> <pre><code>sql1 = """ SELECT distinct th.name, 'MMS' as Status FROM t1 JOIN t2 on t1.id = t2.tid WHERE t2.station= 'MatS' AND t1.name IN ({listthinglist}) """.format(listthi...
<p>Please do not use <code>format</code> for this. The <code>execute</code> function accepts a 'parameters' argument that you would pass your list to. You can modify it like so:</p> <pre><code>sql1 = """ SELECT distinct th.name, 'MMS' as Status FROM t1 JOIN t2 on t1.id = t2.tid WHERE t2.station= 'MatS' AND ...
python|sql|list|pandas
0
19,924
50,448,446
How to change the keras module version?
<p>I got the same error found here in this link</p> <p><a href="https://stackoverflow.com/questions/50293844/pythontypeerror-variable-got-an-unexpected-keyword-argument-constraint?answertab=active#tab-top">https://stackoverflow.com/questions/50293844/pythontypeerror-variable-got-an-unexpected-keyword-argument-constrain...
<p>The link you provided in question section is not accessible anymore.</p> <p>However, (as mentioned by @Jignasha Royala), you can install specific <code>keras</code> by putting it's version detail as below:</p> <pre><code>pip install keras==2.1.6 # (pip install keras==&quot;version name&quot;) </code></pre> <p>For ...
python|windows|tensorflow|keras
0
19,925
45,348,871
Mapping column dataframe with list Python
<p>How to create new column and set values which are results of mapping this dataframe with another object for instance list of lists python?</p> <p>I have pandas dataframe: </p> <pre><code>{'a': [15,10,11,9,7,8], 'b':['smth','smth','smth','smth', 'smth', 'smth']. </code></pre> <p>And list of list: </p> <pre><code>...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>dict</code> created by <code>dict comprehension</code>, values of list has to be unique:</p> <pre><code>df = pd.DataFrame({'a': [15,10,11,9,7,8], 'b':['smth','sm...
python|list|pandas
3
19,926
45,461,346
Append series to dict or list or dataframe from for loop?
<p>I have created a for loop which gives an out like this:</p> <pre><code> SSTIME SCODE 0 0 1 57 3 202 </code></pre> <p>I did reset_index on this series and i got this:</p> <pre><code> SCODE SSTIME 0 0 0 1 1 57 2 3 202 </code></pre> <p>I want...
<p>I think you need not reset_index, but <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> of <code>list of Series</code>:</p> <pre><code>list_ser = [] #sample loop for crate Series for x in L: s = create_function() list_ser.app...
python|pandas|dictionary|dataframe|series
1
19,927
45,440,474
Matplotlib: twinx() wrong values on second axis
<p>I ran into a problem with the <code>plt.twinx()</code> function of <code>matplotlib.pyplot</code> when I tried to plot a secondary x-axis for a primary <code>ln(x)-axis</code>. They should show corresponding values, but with different ticks. For clarity here is what I tried so far in a MWE: </p> <pre><code>import n...
<h2>Here's what's going wrong</h2> <p>It's because the mapping between your two x-scales is non-linear (it's exponential/logarithmic). In effect you've got one axis as a log scale and the other as a normal scale. The two coincide at the endpoints based on how you defined your limits, but not in between. This idea i...
python|numpy|matplotlib|plot
4
19,928
45,517,460
Removing brackets from a numpy array
<p>Let's say I have the following array - </p> <pre><code>X = np.array([[0, 1,5], [3, 7,6], [11,3,2]]) </code></pre> <p>And then I do - </p> <pre><code>X[1,np.delete(range(3),0)] </code></pre> <p>Which gives - </p> <pre><code>array([7, 6]) </code></pre> <p>Basically, I would like to be left with just - </p> <p...
<p>Just try converting it to a list:</p> <pre><code>&gt;&gt;&gt; X[1,np.delete(range(3),0)].tolist() [7, 6] </code></pre>
python|python-3.x|numpy
1
19,929
62,887,380
How to convert a 3D dataset into a 2D dataset on a grid?
<p>My problem is the following:</p> <p>I have a 3D dataset where (x,y) are the cartesian coordinates of a grid and (z) is the intensity/frequency of each point in the grid, named (f).</p> <p>I want to convert this 3D dataset (x,y,f) into a 2D (x,y) dataset, where I'll create new data points in the (x,y) grid according ...
<p>Something like this?</p> <pre><code># make (small) example f = np.random.randint(1,4,(2,3)) yxf = np.c_[(*map(np.ravel,(*np.indices(f.shape),f)),)] yxf # array([[0, 0, 1], # [0, 1, 3], # [0, 2, 3], # [1, 0, 2], # [1, 1, 2], # [1, 2, 2]]) # process yxf[:,:2].repeat(yxf[:,2],axis=0...
python|numpy|cluster-analysis|reshape|flatten
1
19,930
62,524,306
Trying to append new columns in a numpy array using a for loop
<p>I am trying to add new columns using the average of old columns, but I don't know how to loop through the columns from the weights array and append them to the class2 array.</p> <pre><code>class1 = weights[:,sort[popsize-1]] for x in range(1,avgmating+1): new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))...
<pre><code>for x in range(1,avgmating+1): new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))/2 if x == 1: class2 = new else: class2 = np.hstack((class2,new)) </code></pre> <p>That works but I'm sure there is a faster way...</p>
python|arrays|numpy|loops
1
19,931
73,669,044
how to get mean of values in col c, in bins based on col b, in a group defined in col a
<p>I have a pandas dataframe with tens of thousands of rows and about 15 columns, five of which are represented below. The data associated with each RELATEID location are points that have a POINT_TOP value with a potential range of 96 up to 495 (varies per location) in increments of 1, and each point has an associated ...
<p>I tracked your question until a point, and here is the code to reach that point:</p> <pre><code>_, bins = pd.cut(range(96, 495), 40, retbins=True) data.groupby('RELATEID').agg({'POINT_TOP': lambda x: list(pd.cut(x, bins = bins)), 'kclass': 'mean'}) </code></pre> <p>Output</p> <pre><code> POINT_TOP kclass RELATE...
python|pandas|group-by|aggregate|binning
0
19,932
73,670,266
I've been trying to compare 2 columns with similar entries from 2 different excel files
<p>I'm new to pandas and I'm trying to check entries from 2 different excel sheets.</p> <p>Df1-</p> <pre><code> Date Value Date Narration Cod Debit Credit Balance 0 02-Apr-2021 02-Apr-2021 BY XYZ company TRF 0 1112.00 -3244213 1 02-Apr-2022 02-Apr-2022 BY XYZ company CLR 2424 ...
<p>If your requirement was just to find out unmatching entries, then the solution was very easy (thanks to <a href="https://stackoverflow.com/a/53645883/2847330">Pandas Merging 101</a>):</p> <pre class="lang-py prettyprint-override"><code>df1[[&quot;debit&quot;]].merge(df2[[&quot;debit&quot;]], on=[&quot;debit&quot;], ...
python|pandas|dataframe
1
19,933
71,380,044
df.set_index => Index data must be 1-dimensional
<p>I have successfully created a <code>DataFrame df</code> from pandas. However, <code>df.set_index('Time')</code> throws <code>ValueError: Index data must be 1-dimensional</code> and cannot proceed further.</p> <pre><code>df=pd.DataFrame(lst, columns=['Time dtime Open Close High Low Volume'.split()]) df = df.astype({...
<p>Wrong is first line, need remove <code>[]</code> for avoid <code>MultiIndex</code>:</p> <pre><code>df=pd.DataFrame(columns=['Time dtime Open Close High Low Volume'.split()]) print (df.columns) MultiIndex([( 'Time',), ( 'dtime',), ( 'Open',), ( 'Close',), ( 'High',),...
python|pandas|dataframe|valueerror
0
19,934
71,265,228
np.linalg.inv() leads to array full of np.nan
<p>I am trying to calculate the inverse of <a href="https://gigamove.rwth-aachen.de/en/download/67e19a535e5304d72a767d30eb4b1fea" rel="nofollow noreferrer">a matrix</a> via:</p> <pre><code> A = pd.read_csv(&quot;A_use.csv&quot;, header = None) I = np.identity(len(A)) INV = np.linalg.inv(I - A) </code></pre> <p>Howe...
<p>Not all matrices have an inverse. A matrix has and inverse if its determinant is non-zero.</p> <p>Check first whether</p> <pre><code>np.linalg.det(I-A) ~= 0 </code></pre> <p>If it's non-zero, then you should be able to do</p> <pre><code>np.linalg.inv(I-A) </code></pre> <p>Second, make sure <code>I-A</code> does not ...
python|numpy|matrix-inverse
4
19,935
71,303,453
How can I map a list consisting of 136 rows to 7 columns
<p>I can't seem to find a way of doing the following:</p> <p>I have a list of values consisting of 136 rows that looks like this</p> <pre><code>['0.32', '0.32', '0', '0.32', '0.32', 'ABCTRANS', '0.00', '0', '1.96', '1.96', '0', '1.96', '1.96', 'ACADEMY', '0.00', '0' ...up to 136] </code></pre> <p>Now I w...
<p>You can use <code>numpy.reshape</code> to do what you want.</p> <pre><code>import numpy as np import pandas as pd headers = ['Low', 'OPEN', 'Volume', 'Close', 'High', 'Symbol', 'CHANGE', 'Trades'] a = ['0.32', '0.32', '0', '0.32', '0.32', 'ABCTRANS', '0.00', '0', '1.96', '1.96', '0', '1.96', '1.96', '...
python|pandas
1
19,936
71,402,526
Iterating pandas dataframe and changing values
<p>I'm looking to predict the number of customers in a restaurant at a certain time. My data preprocessing is almost finished - I have acquired the arrival dates of each customer. Those are presented in <code>acchour</code>. <code>weekday</code> means the day of the week, 0 being Monday and 6 Sunday. Now, I'd like to c...
<p>So you can get the total customers visiting at a specific time like so:</p> <pre><code>df.groupby(['weekday','time', 'hour'], as_index=False).sum() </code></pre> <p>Then maybe you can calculate the difference between each time window you want?</p>
python|pandas|dataframe
0
19,937
60,707,662
Moving rows in multiple columns into their own columns Python
<p>I've got a dataframe about purchase data which i need to shift around to make it easy to analyse. So far it looks like:</p> <p>''' </p> <pre><code>df = | customers bid/offer price volume 0| 28 B 95 1200 1| 1 O 78 6 2| SOA IFILL May20 F 3| 15 B ...
<p>Solution working if data has first numeric rows splitted by one non numeric rows by <code>price</code> column:</p> <pre><code>#for correct default RangeIndex df = df.reset_index(drop=True) #test numeric rows m = df['price'].str.isnumeric() #join together with removed 1 from index for correct match df1 = pd.concat(...
python|pandas|dataframe
7
19,938
60,498,972
Is there any difference when creating numpy matrix in the following ways?
<p>When I pratice numpy matrix these days, I create a matrix in this way:</p> <pre><code>theta = np.mat([1,1]) temp = np.mat(theta) </code></pre> <p>then I excute the following code for example</p> <pre><code>temp[0,0] = theta[0,0] - 0.3 print(temp, theta) </code></pre> <p>but the answer is so <strong>unexpected</s...
<p>I'll start off with mentioning it's recommended to stop using the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html" rel="nofollow noreferrer">matrix</a> class, and it may be removed in future versions of numpy.</p> <p>The reason for the difference is how the default values are initial...
python|numpy
1
19,939
72,693,645
Getting error saying the truth value of an array with more than one element is ambiguous
<p>...and a suggestion to <code>Use a.any() or a.all()</code>.</p> <p>I am new to python and i am trying to implement a sabr model. I have defined a function with the following parameters:</p> <pre><code>def haganimpliedvol(a,f,k,B,v,t,p): if k != f: z = v/a*math.pow(f*k,(1-B)/2)*math.log(f/k) xz = ...
<p>Pay attention to the variables in this call:</p> <pre><code> for (i,j,k) in zip(k,t,f): calc_vols = np.array([haganimpliedvol(a,f,k,B,v,t,p)]) </code></pre> <p>for the <code>zip</code> to work, <code>k</code>,<code>t</code>, <code>f</code> have to be lists or arrays of matching size;</p> <p>Done use <code>k</co...
python|arrays|numpy
0
19,940
59,504,449
pandas iterate dataframe day wise
<p>I am trying to iterate over data-frame daywise. </p> <p>My data looks like this:</p> <pre><code> open high low close volume date 2019-12-18 09:15:00+05:30 182.10 182.30 180.55 181.30 4252638 2019-12-18 09:30:00+05...
<p>You can try the <code>groupby</code> method and aggregate all other columns in the way you like. For instance: </p> <pre><code>df.groupby(df.date.dt.date)['open'].sum() </code></pre> <p>A OHLC would become:</p> <pre><code>df.groupby(df.date.dt.date).agg({ 'open': 'first', 'high': 'max', 'low': 'min',...
python|python-3.x|pandas
1
19,941
59,642,052
Adding data from a multi-dimensional list to a dataframe
<p>I have a 2 dimensional list called <code>DataList</code>. An example of this list is below:</p> <pre><code>[['Worsheet', 'Field', '', '', 'All Fields', 'Field code', 'Import Sheet', 'Import Column', 'Import Row'], ['Timeliness', 'Requests', '', '', 'Requests', 'A', '1. Timeliness', 'B', '3'], ['Timeliness', '', 'E...
<p>Dataframes are 2D tabular data structures, with rows and columns. You want a particular columnar data. This is basic dataframe creation and column fetch. Refer pandas DataFrame <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">documentation</a></p>
python|pandas
0
19,942
59,819,270
creating a dictionary for big size csv data files using pandas
<p>I'm trying to create a dictionary file for a big size csv file that is divided into chunks to be processed, but when I'm creating the dictionary its just doing it for one chuck, and when I try to append it it passes epmty dataframe to the new df. this is the code I used </p> <pre><code>wdata = pd.read_csv(fileinput...
<p>In order to split the column into words and count the occurrences: <code>df['sentences'].apply(lambda x: pd.value_counts(x.split(" "))).sum(axis=0)</code></p> <p>or </p> <p><code>from collections import Counter result = Counter(" ".join(df['sentences'].values.tolist()).split(" ")).items()</code></p> <p>both seem ...
python|pandas|csv|chunking
1
19,943
59,660,422
Dataframe calculated column not returning numeric values
<p>I have a dataframe (df) which the head looks like:</p> <pre><code> Quarter Body Total requests Requests on-hold Total requests received (excluding on-hold) 1 2019_Q3 A 93 5 2 2019_Q3 B 228 2 3 2019_Q3 C 180 ...
<p>It seems some traling whitespaces, so try remove it by <code>strip</code>:</p> <pre><code>df["Total requests"] = pd.to_numeric(df["Total requests"].str.strip()) df["Requests on-hold"] = pd.to_numeric(df["Requests on-hold"].str.strip()) </code></pre> <p>If possible some non numeric values with trailing values first...
python|pandas
0
19,944
59,699,943
Input shape error in Tensorflow/Keras Conv2D layer
<p>I'm building a convolutional neural network with Keras for the first time, and I just ran into some issues. The purpose of the CNN is to detect patterns in 490x640px grayscale images, which I have converted into 3D numpy arrays. Every image from the image data column of my Pandas dataframe has the shape <code>(490, ...
<p>The problem is that some of your images are not of equal sizes. You can verify that easily, e.g.:</p> <pre><code>shapes = list() for i in X: shapes.append(i.shape) sorted_shapes = np.sort(np.array(shapes).sum(axis=1)) assert sorted_shapes[0] == sorted_shapes[1], 'Not all pictures have equal size.' </code></pre...
python|pandas|tensorflow|keras|conv-neural-network
0
19,945
61,928,857
Dividing data from a large dataframe by data in a smaller dataframe based on indices
<p>I have two data frames. I want to create a new column in the first data frame by dividing by specific data in the second data frame, dependent on a date.</p> <pre><code>import pandas as pd data1 = {'Count': {('2020-02-01','Cat', '0'): 10, ('2020-02-01','Dog', '1'): 7, ('202...
<p>This would work:</p> <pre><code>df1 = df1.reset_index(level=['Animal', 'Dose']) df2 = df2.reset_index(level=['Dose']) df1["New_Value"] = df1['Count'].div(df2['Average']) df1 = df1.reset_index().set_index(['Date', 'Animal', 'Dose']) </code></pre> <p>Output:</p> <pre><code> Count New_Value Dat...
python|pandas|dataframe|multi-index
3
19,946
57,989,994
how to find column whose name contains a specific string
<p>I have following pandas dataframe with following columns</p> <pre><code> code nozzle_no nozzle_var nozzle_1 nozzle_2 nozzle_3 nozzle_4 </code></pre> <p>I want to get columns names nozzle_1,nozzle_2,nozzle_3,nozzle_4 from above dataframe</p> <p>I am doing following in pandas</p> <pre><code> colna...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>df.filter</code></a> <code>regex</code> param here:</p> <pre><code>df.filter(regex='nozzle_\d+') </code></pre>
pandas
3
19,947
58,084,661
How are token vectors calculated in spacy-pytorch-transformers
<p>I am currently working with the <a href="https://github.com/explosion/spacy-pytorch-transformers" rel="nofollow noreferrer"><code>spacy-pytorch-transformer</code></a> package to experiment with the respective embeddings.<br/> When reading the introductionary article (essentially the GitHub README), my understanding ...
<p>It seems that there is a more elaborate weighting scheme behind this, which also accounts for the <code>[CLS]</code> and <code>[SEP]</code> token outputs in each sequence.</p> <p>This has also been confirmed by an <a href="https://github.com/explosion/spacy-transformers/issues/68" rel="nofollow noreferrer">issue po...
python|nlp|pytorch|spacy|spacy-transformers
0
19,948
58,152,454
For each row, I would like to count the frequency of a specific variable repeated in all Y columns in dataframe
<p>I have a data frame which has X rows and Y columns. For each row, I would like to count the frequency of a special variable repeated in all Y columns. I tried doing the <code>df.apply(lambda sum(row[0:y]=="special variable", axis=1)</code>. But this is not returning the correct frequency.</p>
<p>I think what you wanted to do is</p> <pre class="lang-py prettyprint-override"><code>(df == "special variable").sum(axis=0) </code></pre> <p>this will give frequency of "special variable" in each column</p> <p>or</p> <pre class="lang-py prettyprint-override"><code>(df == "special variable").sum(axis=1) </code><...
pandas|python-3.7
1
19,949
57,878,718
How do i use two 2 dimentional arrays to form a 3 dimentional one without using loops in numpy?
<p>Let A and B be two numpy arrays with shapes ( X , Y ) and ( Z , Y ) respectively. I need an array C with shape ( X , Y , Z) where, for every x , y and z, C[ x , y , z ] = A[ x , y ] - B[ z , y ].</p> <p>The fastest way i know to compute C is to subtract B from every row of A, like in this sample of code. </p> <pre...
<p>This is called broadcasting, with <code>B</code> transformed:</p> <pre><code>C = A[:,:,None] - B.T[None,:,:] C.shape </code></pre> <p>Output</p> <pre><code>(10, 8, 3) </code></pre>
python|arrays|numpy
0
19,950
57,801,230
Break a pandas line by symbol and remove repeating element
<p>I have a pandas dataframe of the form: </p> <pre><code> col1 | col2 | col3 | 1 dog$cat 73 2 Inherited pig/dog 21 3 Inherited cat 99 4 Inherited weasel$dog 33 </code></pre> <p>what I want is to remove <code>Inherited</code> from col2, s...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>pandas.Series.str.replace</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</cod...
python|pandas|dataframe
1
19,951
58,056,693
A gradient clipping in Chainer
<p>Can I get a Gradient Clipping function in Chainer?</p> <p>I found some codes in Pytorch Documentation : <a href="https://pytorch.org/docs/stable/_modules/torch/nn/utils/clip_grad.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/_modules/torch/nn/utils/clip_grad.html</a></p> <p>Is there anything like...
<p>how about trying this. just I just re-wrote pyTorch function in Chainer style.</p> <pre><code>import cupy def clip_grad_norm(model, max_norm, norm_type=2): params = list( filter(lambda p : p.grad is not None , model.params()) ) max_norm = float(max_norm) norm_type = float(norm_type) total_norm = 0...
pytorch|gradient|chainer
0
19,952
57,888,427
How to create sheets in an Excel file with pandas and python?
<p>Let's say that I have the following Excel file: <a href="https://i.stack.imgur.com/QAAzO.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I would like to use Python to create an Excel file for each sheet, with all the columns as well. So in Sheet1 to have all the lines where "Sheet1" is menti...
<p>I suppose the below correction in your code should work fine for your expected output.</p> <pre><code>for sheet in sheets: df.loc[(df['Sheet'] == sheet)].to_excel(writer, sheet) </code></pre> <p>Let me know if this works :)</p>
excel|pandas|python-2.7
1
19,953
57,741,176
How to create dataframe of tokenized words (columns) per sentence (rows)?
<p>I have the following text:</p> <p><strong>"Hi there, my name is sam! I love spicy hand pulled noodles. I also like to game alot."</strong></p> <p>My goal is to convert this paragraph into a dataframe of tokenized words per sentences. (Where the number of rows is equal to the number of sentences, and the number of ...
<p>If the 1st prefixed column starts with <code>1</code> (<code>w1</code>):</p> <pre><code>In [350]: df.join(pd.DataFrame(df['tokens'].tolist(), columns=[f'w{i}' for i in range(1, df['tokens'].str.len().max() + 1)])).fillna(np.nan) Out[350]: sentences ...
python|python-3.x|pandas
1
19,954
57,872,554
Converting tf.keras model to estimator makes loss worst
<p>I did an experiment to compare tf.keras's performance before and after conversion to estimator and got very different loss: 1) tf.keras model (No estimator) : 1706.100 RMSE (+/- 260.064) 2) tf.keras converted to estimator : 3912.574 RMSE (+/- 132.833)</p> <p>I'm sure I did something wrong in estimator conversion,...
<p>More observation from me. I tried another neural network method (MLP). In that case, keras and tf.keras prediction is very close. Conclusion is that the gap introduced by estimator conversion only happens to certain tf.keras libraries and layers. The culprit are ConvLSTM2D and Flatten which I suspect tf.keras may ha...
tensorflow|keras|deep-learning|tf.keras
0
19,955
34,247,582
python geopandas TclError: Can't find a usable init.tcl in the following directories:
<p>Trying to plot something using geopandas and was also trying to do similar mapping using bokeh, but ran into the same error spent too many hours googling and can't seem to fix it. </p> <p>I'm running on Mac OS X 10.10.5 running ipython notebook (python 2.7.10) in a virtualenv. I've installed ActiveTLC 8.6.4 on the ...
<p>To close this, it was a path issue. I uninstalled anaconda and it seemed to clear things up. Thanks to tcaswell for the tip.</p>
python|matplotlib|tkinter|ipython|geopandas
1
19,956
34,376,144
Convert array of ints to array of characters and vice versa in Julia
<p>In Python/NumPy, I can convert arrays of ints to arrays of characters quite easily. How can I do this in Julia?</p> <p>For example in Python:</p> <pre><code>In [6]: np.array(["A", "T", "C"]).view(np.int32) Out[6]: array([65, 84, 67], dtype=int32) </code></pre> <p>And vice versa</p> <pre><code>In [15]: np.array([...
<p>Take a look at <a href="http://docs.julialang.org/en/release-0.4/stdlib/arrays/#Base.reinterpret" rel="nofollow"><code>reinterpret</code></a>:</p> <pre><code>julia&gt; a = ['A' 'T' 'C'] 1x3 Array{Char,2}: 'A' 'T' 'C' julia&gt; b = reinterpret(Int32, a) 1x3 Array{Int32,2}: 65 84 67 </code></pre> <p>That make...
python|numpy|julia
4
19,957
36,710,846
Python / Numpy: Triangle mask from point mask
<p>I'm working with a triangulated mesh consisting of points 3 x n and triangles specified by the point indices 3 x m. I can easily plot that e.g. using mlab</p> <p><code>mesh = mlab.triangular_mesh(p[0,:],p[1,:],p[2,:],t.T</code></p> <p>I am also generating a mask masking points which are out of bounds or <code>nan<...
<p>So you have a <code>points</code> array of shape <code>(3, n)</code>, a <code>triangles</code> array of shape <code>(3, m)</code> and a <code>point_mask</code> boolean array of shape <code>(n,)</code>, and would like to create a <code>triangle_mask</code> of shape <code>(m,)</code> holding <code>True</code> at posit...
python|numpy|matplotlib|mayavi
1
19,958
55,050,024
How to get values from dataframe with dynamic columns
<p>Python newbie here, I am not able to create a function which can extract certain columns' values into another form. I have tried to run a loop multiple times to get the data, but I am not able to find a good pythonic way to do it. Any help or suggestion would be welcome. </p> <p>PS: The column with "Loaded with" is...
<p>May be something like:</p> <pre><code>m=df.loc[:,df.filter(like='item').columns] df['Item1']=m.filter(like='0').astype(float).prod(axis=1) df['Item2']=m.filter(like='1').astype(float).prod(axis=1) </code></pre> <p>Output:</p> <pre><code> index Loadedwith item_0L item_0B item_0H item_1L item_1B ite...
python|pandas|dataframe
1
19,959
54,905,677
Python get coordinate with pair of nans
<p>I have a dataframe like this </p> <pre><code>&gt;&gt;df1 = pd.DataFrame({ 'A': ['1', '2', '3', '4', '5'], 'B': ['1', '1', '1', '1', '1'], 'C': ['c', 'A1', NaN, 'c3', Nan], 'D': ['d0', 'B1', 'B2', Nan, 'B4'], 'E': ['A', Nan, 'S', Nan, 'S'], 'F': ['3', '4', ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> with filter index values by missing values:</p> <pre><code>s = df1.stack(dropna=False) L = [list(x) for x in s.index[s.isna()]] print (L) [[1, 'E'], [2, 'C'], [2, 'G'], [3...
python|pandas|nan
4
19,960
54,940,961
finding the difference of sum in percentage after groupby in pandas
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({'x': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], 'y': [0,1,0,1,0,1,0,1], 'z':[100, 102, 110, 115, 200, 202, 230, 240]}) x y z 0 a 0 100 1 a 1 102 2 a 0 110 3 a 1 115 4 b 0 200 5 b 1 202 6 b 0 230 7 b 1 240 </code></pre> <...
<p>You could <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> both <code>x</code> and <code>y</code> and take the <code>sum</code> as you already do, and then use <a href="https://pandas.pydata.org/pandas-docs/stable/re...
python|pandas
1
19,961
49,395,369
Tensorflow-gpu 1.5 with cuda 8.0 and cudnn v7.1 for cuda 8.0
<p>I first installed cuda 9.0 and cudnn for cuda 9.0 and the latest tensorflow-gpu 1.6. But I noticed my nvidia-driver 384.111 doesn't support cuda 9.0. SO I uninstalled cuda 9.0, cudnn and tensorflow-gpu 1.5 and reinstalled tensorflow-gpu 1.5, cuda8.0 and cudnn v7.1 for cuda 8.0. But when I import tensorflow, it alway...
<p>I assume that you are installing TF using <strong>pip install</strong>. <a href="https://www.tensorflow.org/install/install_linux" rel="nofollow noreferrer">Tensorflow install page</a> (currently, version 1.6) mentions than that CUDA® Toolkit 9.0 along with cuDNN v7.0 are the requirements for your installation. </p>...
tensorflow|importerror|cudnn
1
19,962
73,337,670
How to create Boolean if a Pyspark column string is found in a list of strings?
<p>I have a Spark Dataframe that has a column containing strings. These strings are referencing beverages, but can also include amounts / volumes / etc (there is no consistency so a regular expression can help clean this up, but can not resolve this). As a way to circumvent that I was hoping to use a filter to determin...
<p>Assume this is your drinks array (or list):</p> <pre><code>val drinks = Array(&quot;SODA&quot;, &quot;WATER&quot;, &quot;COFFEE&quot;, &quot;TEA&quot;, &quot;JUICE&quot;) </code></pre> <p>We can convert this to a regex expression so we can apply it in <code>rlike</code> API:</p> <pre><code>val regex = drinks.map(x =...
python|pandas|string|apache-spark|pyspark
1
19,963
73,296,396
RuntimeError: Given groups=1, weight of size [6, 1, 5, 5], expected input[128, 3, 218, 178] to have 1 channels, but got 3 channels instead
<p>Yes, I have looked and tried solution from other related questions. Let me explain.</p> <p><strong>Description:</strong> So, I am doing adversarial training and I’ve used code from <a href="https://github.com/ttchengab/FGSMAttack" rel="nofollow noreferrer">this Github</a> repo. It uses Pytorch to train model on MNIS...
<p>Hi your input does not match due to the fact your input is not a log of 2, your final view makes it as such</p> <pre class="lang-py prettyprint-override"><code>import torch import torch.nn as nn import torch.nn.functional as F class LeNet5(torch.nn.Module): def __init__(self): super(LeN...
python|tensorflow|machine-learning|pytorch|conv-neural-network
0
19,964
73,280,632
DataFrame from list of string dicts
<p>So I have a list where each entry looks something like this:</p> <pre><code>&quot;{'A': 1, 'B': 2, 'C': 3}&quot; </code></pre> <p>I am trying to get a dataframe that looks like this</p> <pre><code> A B C 0 1 2 3 1 4 5 6 2 7 8 9 </code></pre> <p>But I'm having trouble converting the format i...
<h4><code>eval</code> is not safe. Check <a href="https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval"><code>this comparison</code></a>.</h4> <p>Instead use <a href="https://www.educative.io/answers/what-is-astliteralevalnodeorstring-in-python" rel="nofollow noreferrer"><code>ast.literal...
python|pandas|dataframe
2
19,965
73,284,899
How to correctly define weights and biases in a PyTorch neural network to get output of correct shape?
<p>I'm attempting to pass some data of shape <code>[70,1]</code>, <code>[70,1,1]</code>, and <code>[70,1]</code> into a neural network of linear layers for which I have assigned weights and biases. I am expecting an output of shape [70,1], but I am constantly getting the following error:</p> <pre><code>RuntimeError ...
<p>The shape of <code>weight_last</code> must be <code>[1,3]</code> instead of just <code>[3]</code> to prevent the matrix multiplication error.</p>
python|machine-learning|neural-network|pytorch
1
19,966
67,343,544
Plot shapefiles with geometry point and line on a single plot in python
<p>I have 3 shapefiles that I want to layer/ superimpose on top of each other, so all the plots can be viewed on a single map. I have <a href="https://hub.arcgis.com/datasets/RPCGB::bus-stops/data?geometry=-87.884%2C33.312%2C-85.798%2C33.713&amp;page=26" rel="nofollow noreferrer">bus stops</a>, <a href="https://hub.arc...
<p>Here is the code that I used</p> <pre><code>BJCTABusStops = gpd.read_file(r'Bus_Stops-shp\Bus_Stops.shp') ExistingRoutesMap = gpd.read_file(r'Birmingham_Area_Transit_Routes-shp\Birmingham_Area_Transit_Routes.shp') ZoneMap = gpd.read_file(r'Zoning_Map_for_Jefferson_County%2C_AL\Zoning_Map_for_Jefferson_County%2C_AL.s...
python|matplotlib|shapefile|geopandas
1
19,967
67,425,822
Numpy identity values for ufunc maximum and minium
<p>Why are <code>np.maximum.identity</code> and <code>np.minimum.identity</code> both equal to <code>None</code>? I would expect the identity of maximum to be <code>-np.inf</code> and <code>np.inf</code> for minimum. Using <code>None</code> as an operand to maximum/minimum returns an error, so there must be some intern...
<p>Additionally to the comments, the problem with <code>np.inf</code> is typing. Indeed, if <code>-np.inf</code> would be used for the maximum, the result would be strange for integers and probably just wrong for structured types (actually, any non-floating-points types). Here is an example:</p> <pre class="lang-py pre...
numpy
0
19,968
67,484,449
InternalError: stream did not block host until done; was already in an error state
<p>stream did not block host until done; was already in an error state how to fix it using tensorflow keras</p> <pre><code>model.compile( optimizer=&quot;adam&quot;, loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['acc']) model.fit(X_train_scaled, y_train, epochs=5) </code></pre> <p>t...
<p>Restarting the notebook fixed this issue for me. If this doesn't fix it, you can try updating the GPU drivers.<br> Also, a similar issue is available on GitHub : <a href="https://github.com/tensorflow/tensorflow/issues/1060" rel="nofollow noreferrer">Link to the Issue</a></p>
python|tensorflow|keras|model-fitting
0
19,969
67,451,125
Create row values in a column with data from previous row in Python Pandas
<p>I am trying to create a new column in which the value in the first row is 0 and from the second row, it should do a calculation as mentioned below which is</p> <pre><code>ColumnA[This row] = (ColumnA[Last row] * 13 + ColumnB[This row])/14 </code></pre> <p>I am using the python pandas shift function but it doesn't se...
<pre class="lang-py prettyprint-override"><code>test = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9]) test = pd.DataFrame(test, columns = ['ABC']) test[&quot;res&quot;] = test[&quot;ABC&quot;] test.iloc[0]['res'] = 0 # Initialize the first row as 0 test[&quot;res&quot;] = test.res + test.res.shift() t...
python|pandas|lag|shift
0
19,970
67,436,480
select string over date in python panda
<p>I'm trying to take the highest value from my data here. The last_release field got the string 'now' and i want 'now' to be picked over other dates if my code encounters it. Currently the code picks the most recent date but not the 'now' string. All that i tried to fix this issue is not materializing. Any help would ...
<p>Be 100% consistent in how you switch between strings, dates and strings and it's simple.</p> <pre><code>fmt = &quot;%m/%d/%Y&quot; now = pd.to_datetime(&quot;now&quot;).strftime(fmt) df[&quot;last_release&quot;] = df[&quot;last_release&quot;].str.replace(&quot;now&quot;,now) df['last_release'] = pd.to_datetime(df[...
python|pandas|dataframe
0
19,971
34,716,591
Setting yahoo finance date as dataframe index
<p>i have a python function that stores the yahoo finance data to a dataframe.</p> <pre><code>from pandas.io.data import DataReader bars= DataReader(symbol, "yahoo",hist_date, today) </code></pre> <p>and i get the result returned to bars as follows</p> <p>DataFrame: </p> <pre><code> O...
<p>First, let me retrieve 5 days of historical data for Google from Yahoo:</p> <pre><code>from pandas.io.data import DataReader import datetime as dt today = dt.datetime.today().strftime('%Y-%m-%d') hist = (dt.datetime.today()-dt.timedelta(7)).strftime('%Y-%m-%d') df = DataReader('GOOG', 'yahoo', hist, today) df ...
python|pandas|dataframe|yahoo-finance
2
19,972
60,077,948
Pandas dropna with multilevel column index
<p>So I have got this Pandas DataFrame with multilevel index for the columns:</p> <pre><code> group1 group2 group3 1 2 1 2 1 2 0 ... ... NaN ... ... ... 1 NaN ... ... ... ... ... 2 ... ... ... ... NaN ... </code></pre> <p>Now i want to drop the rows where the columns <code>...
<p>Seems like we can not pass the index <code>level</code> in <code>dropna</code> , so we could do </p> <pre><code>df.loc[:,['group2', 'group3']].isna().any(1) </code></pre> <p>Then </p> <pre><code>df=df[df.loc[:,['group2', 'group3']].isna().any(1)] </code></pre>
python|pandas
3
19,973
59,914,670
Pandas create funneling based on user activity
<p>I have this dataframe</p> <pre><code>user created_at session_count event_name Alpha 2019-11-01 07:00:00+07:00 1 A Alpha 2019-11-01 07:00:01+07:00 1 B Alpha 2019-11-01 07:00:02+07:00 1 C Alpha 2019-11-01 07:00:03+07:00 ...
<p>In part, the approach proposed by Datanovice makes sense. <strong>The bad thing is that in this way we have to modify the data frame every time we make a new query</strong>. I think it is best that you <strong>first obtain the data frame from which you want to obtain the information (and that you do only once)</stro...
python|pandas
2
19,974
60,123,947
Groupby for large number columns in pandas
<p>I am trying to loop through multiple excel files in pandas. The structure of the files are very much similar, the first 10 column forms a key and rest of the columns have the values. I want to group by first 10 columns and sum the rest.</p> <p>I have searched and found solutions online for similar cases but my prob...
<p>Just use <code>df.columns</code> which has the list of columns, you can then use a slice on that list to get the 10 leftmost columns.</p> <p>This should work:</p> <pre><code>df.groupby(df.columns[:10].to_list()).sum() </code></pre>
python|pandas|pandas-groupby
1
19,975
65,446,088
how to insert numbers (i+1) in ndarray at the beginning?
<p>I have ndarray in npz file and I'm trying to insert numbers at index 0 and inserted numbers should be increase by 1. Below is my array</p> <pre><code>data = [[[3.56, 7.94, 1.78], [8.23, 1.25, 4.80], [0.51, 8.23, 5.67], [9.56, 7.94, 2.78], [5.23, 7.25, 0.80],...]] </code></pre> <p>And the resulted ndarray should like...
<p>You should do:</p> <pre><code>import numpy as np data = np.array([[[3.56, 7.94, 1.78], [8.23, 1.25, 4.80], [0.51, 8.23, 5.67], [9.56, 7.94, 2.78], [5.23, 7.25, 0.80]]]) res = np.insert(data, 0, np.arange(data.shape[1]), axis=2) print(res) </code></pre> <p><strong>Output</strong></p> <pre><code>[[[0. 3.56 7.94 1....
python|numpy|data-structures|numpy-ndarray
1
19,976
50,101,228
concatenate arrays on axis=3 while first dimension is different
<p>l have about 20 different data shape. l would like to concatenate them on <code>axis=3</code></p> <pre><code>data_1=dim(1000,150,10) data_2=dim(1000,150,10) data_3=dim(1000,150,10) data_4=dim(1000,150,10) </code></pre> <p>and</p> <pre><code>features_1=dim(1000,150,10) features_2=dim(1000,150,10) features_3=dim(10...
<p>This can be done either by list comprehension or if the result should be an array with <code>np.frompyfunc</code>:</p> <pre><code># create example &gt;&gt;&gt; data = np.array([np.arange(n*12).reshape(n, 2, 6) for n in range(2, 5)]) &gt;&gt;&gt; features = np.array([np.ones((n, 2, 6), int) for n in range(2, 5)]) &g...
python-3.x|numpy|concatenation
1
19,977
63,825,262
Is there any way to create a loop which fills down values to the next empty 5 rows in a column?
<p>I have a <code>dtype: object</code> column in my <code>df</code> and I would like to fill down values to the empty cells. None of my attempts made the job for me including <code>df.fillna(method='ffill', inplace=True)</code>.</p> <p>So what I did was I converted the column into a list, created a list with values I w...
<p>Try this</p> <pre><code>indexes = [i for i in range(len(a)) if a[i] != 'nan'] for idx in indexes: a[idx: idx + 6] = [a[idx]] * 6 print(a) </code></pre> <p><strong>Output:</strong></p> <pre><code>['nan', 'nan', 'nan', 'Loaded volume_Road', 'Loaded volume_Road', 'Loaded volume_Road', 'Loaded volume_Road', 'Loaded...
python|pandas|loops|fillna
1
19,978
64,138,937
How do you extract the date format "Month_name date, year" into separate columns of date, month and year in Pandas? For eg. "August 30, 2019"
<p>I've seen extractions of date, month and year from data format: &quot;DD-MM-YYYY&quot; and the like. (Where the month is numbered rather than named)</p> <p>However, I have a dataset which has date values in the format: &quot;Month_name date, year&quot;. Eg. &quot;August 30, 2019&quot;.</p>
<p>Assume that your DataFrame contains <em>TxtDate</em> column, with date strings:</p> <pre><code> TxtDate 0 August 30, 2019 1 May 12, 2020 2 February 16, 2020 </code></pre> <p>The first step is to convert the source column to <em>datetime</em> type and save it in a new column:</p> <pre><code>df['...
pandas|dataframe|datetime
1
19,979
63,902,081
How to use softmax in tensorflow
<p>I made a TensorFlow sample which takes an integer and divides it by 5 and classified into the remainder.</p> <p><a href="https://colab.research.google.com/drive/1CQ5IKymDCuCzWNfgKQrZZSL3ifyzRJrA?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1CQ5IKymDCuCzWNfgKQrZZSL3ifyzRJrA?usp=shari...
<p>After some trial and error, I found a solution.</p> <p>the Input is just an integer and I think it is 1 dimension. it looks like as follows X = [100 , 15, 48, 17, 22]</p> <p>I try the test input's shape as follow: X = [[1,0,0] , [0,1,5], [0,4, 8] , [0,1,7] , [0,2,2]]</p> <p>The loss is decreased as expected</p>
tensorflow
0
19,980
64,152,211
My Keras Sequential Model is giving me a 0 accuracy
<hr /> <p>I'm trying to create a model that could predict the premier league games results. And when trying to do this the model keeps giving me 50 - 66 accuracy when training and 0 when testing with some test data. I just started using keras and tensorflow so I apologize for the bad code</p> <pre><code>from tensorflow...
<p>You'll need to supply the target data for evaluation. i.e.</p> <pre><code>acc = model.evaluate(x_test,y_test) </code></pre>
python|numpy|machine-learning|keras|neural-network
0
19,981
63,883,611
running pytorch geometric get CUDA error: CUBLAS_STATUS_NOT_INITIALIZED when calling `cublasCreate(handle)`
<p>I am running the code in this notebook. <a href="https://colab.research.google.com/github/zaidalyafeai/Notebooks/blob/master/Deep_GCN_Spam.ipynb#scrollTo=UjoTbUQVnCz8" rel="nofollow noreferrer">https://colab.research.google.com/github/zaidalyafeai/Notebooks/blob/master/Deep_GCN_Spam.ipynb#scrollTo=UjoTbUQVnCz8</a> I...
<p>In my case, I need to make sure that my edge_attributes where in the range of [0,1].</p> <p>See <a href="https://github.com/rusty1s/pytorch_geometric/issues/716#issuecomment-537475199" rel="nofollow noreferrer">here</a></p>
pytorch
-1
19,982
47,000,992
How to uninstall wrong Tensorflow version?
<p>I commit a silly mistake and installed the wrong version of Tensorflow (I'm using windows but installed the mac version). How do I uninstall the wrong version? Also I found out that Tensorflow can only be installed in the Python 3.5 version(mine is 3.6), is that true? How to downgrade my Python without losing all li...
<p>Just use: <code>pip3 uninstall tensorflow</code></p>
python|tensorflow
0
19,983
63,287,950
Is there an easier way to create a df out of this information?
<p>I have information that is stored in multiple layers json format which I want to convert to a pandas dataframe, so far I've been doing it this way and I'm sure there is a far more readable solution</p> <p>At the moment Im just creating empty lists and filling them up by appending each wanted item</p> <p>the calls an...
<p>I downloaded the JSON file for calls from GitHub, and did a small amount of parsing.</p> <pre><code>import pandas as pd import requests filename = 'https://raw.githubusercontent.com/Quaniful/Pub/master/C.json' field_types = { 'symbol' : 'string', 'strikePrice' : 'float', 'put...
python|pandas|loops|for-loop|readability
0
19,984
63,237,199
How does one compute the norm of a function in python?
<p>I want to compute the functional norm of a function. My use case is the distance of two function but that is not as important as computing this in a correct manner in python. Looking at the docs I did:</p> <pre><code>import numpy as np import scipy.integrate as integrate def functional_diff_norm(f1, f2, lb, ub, p=2...
<p>You should follow the formula in the doc string</p> <pre><code>norm = integrate.quad(lambda x: abs(f1(x) - f2(x))**p, lb, ub)[0]**(1/p) </code></pre>
python|numpy|numerical-methods|numerical-integration
1
19,985
63,225,696
Convert PostgreSQL ARRAY_AGG query to Pandas DataFrame code
<p>This is PostgreSQL query and I want it to write it using Pandas data-frame.</p> <pre class="lang-sql prettyprint-override"><code>SELECT A.id, ARRAY_AGG(STRUCT( B.b_id, C.c_id, C.code, c.desc )) AS conditions FROM A JOIN B ON A.id = B.id JOIN C ON B.b_id = C.c_id </code></...
<p>If you want to use it in a DataFrame structure you have to dissolve the <code>ARRAY_AGG</code> because the DataFrame do not support this structure.</p> <pre><code>SELECT A.id, B.b_id, C.c_id, C.code, C.desc FROM A JOIN B ON A.id = B.id JOIN C ON B.b_id = C.c_id </code></pre> <p>And then you can ...
python|sql|pandas|postgresql|pandas-groupby
0
19,986
67,874,010
How to save tensor with numpy?
<p>I need to save tensor by transform the x[-1] to numpy matrix, and then save it as a pkl file.</p> <pre><code>def forward(self, x): x=self.forward_features(x) </code></pre> <p>What does x[-1] means ? How can I transform x to numpy ..</p> <pre><code>Y=[] Y=x.transform() With open('result.pkl','w') as file ...
<p><code>x[-1]</code> gets you the last item on the list.</p> <p>If <code>x</code> is a list, do <code>np.array(x)</code> to convert the list to a numpy array.</p> <p>To save <code>x</code> to a pickle file, do</p> <pre><code>import pickle import numpy as np x = np.array([1, 2, 3]) with open('res.pkl', 'wb') as df_fi...
python|numpy|tensorflow|object-detection|feature-extraction
0
19,987
67,669,233
Enhancing performance of pandas groupby&apply
<p>These days I've been stucked in problem of speeding up groupby&amp;apply,Here is code:</p> <pre><code>dat = dat.groupby(['glass_id','label','step'])['equip'].apply(lambda x:'_'.join(sorted(list(x)))).reset_index() </code></pre> <p>which cost large time when data size grows. I've try to change the groupby&amp;apply t...
<p>I think you can consider to use <code>multiprocessing</code><br /> Check the following example</p> <pre><code>import multiprocessing import numpy as np # The function which you use in conjunction with multiprocessing def loop_many(sub_df): grouped_by_KEY_SEQ_and_count=sub_df.groupby(['KEY_SEQ']).agg('count') ...
pandas|pandas-groupby|pandas-apply
0
19,988
41,639,182
Diagonal Block Multiplication via Tensor Multiplication in Numpy
<p>Is there an expression (perhaps using <code>np.tensordot</code>) that most expressively captures a sparse matrix vector multplicatiuon between a block matrix of diagonal blocks and a vector of the corresponding size?</p> <p>I have a working implementation that performs the exact operations I want, but I used two py...
<p><strong>Approach #1 :</strong> You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('ijk,jk-&gt;ik', diag_block, x.reshape(outer_size, -1)).ravel() </code></pre> <p>Basically, we are keeping th...
python|numpy
2
19,989
61,231,420
Checking for a single column name inside a for loop. How to stop repeating this check over and over once it has been satisfied?
<p>This feels like something a 3 year old could figure out, I'm almost embarrassed to ask. </p> <p>I want to print out the mean of each column in a dataframe. </p> <p>But I don't want to print the mean if it's a certain column. So I check for this column and then skip it and move onto the next columns. </p> <p>The p...
<p>A <code>for</code> loop runs code for every element in the iterable. If there is a line that checks a condition within the <code>for</code> loop, it'll be checked for <em>every</em> iteration of that loop. Even if you store a variable that tells it whether or not to check, you'll be checking the value of that variab...
python|pandas
3
19,990
61,236,092
What explains the performance difference in Dask between DataFrame.assign(**kwargs) and dd[x]=y when appending multiple columns?
<p>While migrating some code from Pandas to Dask I found an enormous performance difference between modifying a Dask dataframe by calling <code>DataFrame.assign()</code> with multiple columns vs modifying it with multiple <code>DataFrame.__setitem__()</code> (aka <code>dataframe[x]=y</code>) calls.</p> <p>With imports...
<p>Two main reasons:</p> <ol> <li>The for loop generates a larger task graph (one new layer per item in the loop), compared to the single additional task from the <code>assign</code>.</li> <li><code>DataFrame.__setitem__</code> is actually implemented in terms of assign: <a href="https://github.com/dask/dask/blob/366c...
python|pandas|dataframe|dask
0
19,991
61,580,468
Broadcast error HDF5: Can't broadcast (3, 2048, 1, 1) -> (4, 2048, 1, 1)
<p>I have received the following error: </p> <p>TypeError: Can't broadcast (3, 2048, 1, 1) -> (4, 2048, 1, 1)</p> <p>I am extracting features and placing them into a hdf5 dataset like this:</p> <pre><code>array_40 = hdf5_file.create_dataset( f'{phase}_40x_arrays', shape, maxshape=(None, args.ba...
<p>I think you are confused on use of <code>maxshape=()</code> parameter. It sets maximum allocated dataset size in each dimension. The first dataset dimension is set to <code>dataset_length</code> at creation with <code>maxshape[0]=None</code> which allows for unlimited growth in size. The size of second dataset dimen...
python|pytorch|hdf5|h5py
0
19,992
61,585,380
How to not set value to slice of copy
<p>I am trying to replace string values in a column without creating a copy. I have looked at the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy" rel="nofollow noreferrer">docs</a> provided in the warning and also this <a href="https://stackoverflow.com/que...
<p>Let's start from some improvements in the initial part of your code:</p> <ol> <li><p>The leftmost column of your input file is apparently the <strong>index</strong> column, so it should be read as the index. The consequence is some different approach to the way to access rows (details later).</p></li> <li><p>The <e...
python|pandas
2
19,993
61,320,661
Getting values of trainable parameters in tensorflow
<p>I am trying to extract all trainable weights from a model. In pytorch a similar thing would be done by a single line <code>p.grad.data for p in model.parameters() if p.requires_grad</code>, however I'm struggling to come up with a simple solution in TF.</p> <p>My current attempt looks like this:</p> <pre><code>ses...
<p>It is easier you do it by using custom callback Fn, and trading with your custom actions follows !</p> <pre><code>class custom_callback(tf.keras.callbacks.Callback): tf.summary.create_file_writer(val_dir) def _val_writer(self): if 'val' not in self._writers: self._writers['val'] = tf.summary.create_fil...
python|tensorflow
0
19,994
68,814,267
SQL Update case when in Python
<p>I would like to reproduce the following SQL code in pandas. Does anynone have a suggestion?</p> <pre><code>UPDATE [Table] SET [Column1] = CASE WHEN [Column2] IS NULL AND [Column3] IS NULL THEN [Column3] WHEN [Column2] IS NOT ...
<p>Glad to answer on your question. I suggested you to change code as below :</p> <pre><code># Set a default value. df['Column1'] = df['Column3'] # Set Column2 only when Column2 is not Null and Column3 is Null. df['Column1'][(df['Column2'] != None) &amp; (df['Column3'] == None)] = df['Column2'] # Other case is set Colu...
python|sql|pandas
1
19,995
68,530,807
Python & Pandas: appending data to new column
<p>With Python and Pandas, I'm writing a script that passes text data from a csv through the pylanguagetool library to calculate the number of grammatical errors in a text. The script successfully runs, but appends the data to the end of the csv instead of to a new column.</p> <p>The structure of the csv is:</p> <p><a ...
<p>Instead of using a loop, you might consider <code>lambda</code> which would accomplish what you want in one line:</p> <pre><code>df[&quot;error_count&quot;] = df[&quot;text&quot;].fillna(&quot;&quot;).apply(lambda x: len(api.check(x, api_url='https://languagetool.org/api/v2/', lang='en-US')[&quot;matches&quot;])) &...
python|pandas
4
19,996
68,577,065
Highlight the cells in different color if not exact dup
<p>I have this dataframe. If the <strong>Description</strong> is the same then the job entry should be exactly the same.</p> <pre><code>mycol = ['Title', 'Location', 'Company', 'Salary', 'Sponsored', 'Description'] mylist=[('a', 'b', 'c', 'd', 'e', 'f'), ('a', 'b', 'c', 'd2', 'e', 'f'), ('g', 'h', 'i', 'j', 'k', 'l' ),...
<p>We can clear the rows where the description is <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>duplicated</code></a>, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.ffill.html" rel=...
pandas|pandas-styles
2
19,997
36,585,563
Weights for histogram in pandas
<p>I have a pandas dataframe (call it data) with categorical and continuous values that look like this:</p> <pre><code>INDEX AGE SEX INCOME COUNTRY INSTANCE_WEIGHT 1 25 M 30000 USA 120 2 53 F 42000 FR 95 3 37 F 22000 USA 140 4 18 M 0 FR 110...
<p>You should use the 'weights' argument of the <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html" rel="noreferrer">matplotlib 'hist' function</a>, which is also available through the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="noreferrer">panda...
python|pandas|matplotlib
14
19,998
5,480,694
NumPy: calculate averages with NaNs removed
<p>How can I calculate matrix mean values along a matrix, but to remove <code>nan</code> values from calculation? (For R people, think <code>na.rm = TRUE</code>).</p> <p>Here is my [non-]working example:</p> <pre><code>import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.n...
<p>I think what you want is a masked array:</p> <pre><code>dat = np.array([[1,2,3], [4,5,'nan'], ['nan',6,'nan'], ['nan','nan','nan']]) mdat = np.ma.masked_array(dat,np.isnan(dat)) mm = np.mean(mdat,axis=1) print mm.filled(np.nan) # the desired answer </code></pre> <p><strong>Edit:</strong> Combining all of the timing ...
python|numpy|nan
35
19,999
53,022,683
Combining multiple Pandas data frames based on specific column
<p>Suppose I have multiple Pandas data frames, each with multiple rows and columns, the first of which contains the ID of something. What I'd like to do is pretty simple what I failed using merge, join, concat etc... If the first column of df1 and df2 is the same, then append column 2 till the end of df2 to df1, otherw...
<p>use merge</p> <pre><code>pd.merge(df1,df2,left_index=True,right_index=True) 0_x 1_x 2_x 0_y 1_y 2_y A 1 2 3 1 2 3 B 4 7 11 4 7 11 C 5 8 12 5 8 12 D 6 9 13 6 9 13 def myFunc(df1,df2): if len(np.intersect1d(df1.index.values, df2.index.values)) == len(df1.index.v...
python|pandas|dataframe|merge
0