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 |
|---|---|---|---|---|---|---|
360,100 | 54,177,124 | DataFrame.corr() - Pearson linear correlation calculated with the same duplicated data? | <p><code>x=[0.3, 0.3, 0.3, ..., 0.3]</code> (number of 0.3: 10)</p>
<pre><code>y=x
</code></pre>
<p>What is the linear correlation coefficiency between <code>x</code> and <code>y</code>? </p>
<p>For this <code>x</code> and <code>y</code>, all pairs points to the same point <code>(0.3, 0.3)</code>. Can we say ... | <p>Using the Pearson R coefficient, which assumes a normal distribution of the data, on a bunch of constants is a mathematically undefined operation.</p>
<pre><code>xm = x - x.mean()
ym = y - y.mean()
r = sum(xm * ym) / np.sqrt( sum(xm**2) * sum(ym**2) )
</code></pre>
<p>In other words, if there is no variation in yo... | python|pandas|pearson-correlation | 0 |
360,101 | 54,244,171 | How do I loop over each row in a pandas groupby()? | <p>Let's say I have: </p>
<p><code>df = pd.DataFrame({'a' : [1, 2, 3, 4, 5] , 'b' : ['cat_1', 'cat_1', 'cat_2', 'cat_2', 'cat_2']})</code></p>
<p>I perform a groupby:</p>
<p><code>df.groupby(['b']).agg(['count', 'median'])</code></p>
<p>I would like to iterate through the rows that this call returns, for example:</... | <p>You've misunderstood: <code>df.groupby(['b']).agg(['count', 'median'])</code> returns an in-memory <strong>dataframe</strong>, <em>not</em> an <strong>iterator</strong> of groupwise results.</p>
<p>Your result is often expressed in this way:</p>
<pre><code>res = df.groupby('b')['a'].agg(['count', 'median'])
print... | python|pandas | 5 |
360,102 | 53,850,395 | When using tf.data.TFRecordDataset as the input pipeline, how to have sess.run() or eval() invoked more than once in the same iteration round? | <p>With <code>tensorflow</code>, I've made a <code>dataset = tf.data.TFRecordDataset(filename)</code> and <code>iterator = dataset.make_one_shot_iterator()</code>. Then in each round <code>iterator.get_next()</code> would give out a mini-batch of data as input.</p>
<p>I am training a network with <code>Dropout</code> ... | <p>Merry Christmas!</p>
<p>Thanks so much for Santa's gift :-) </p>
<p>I've just been guided to <a href="https://github.com/buptlj/learn_tf" rel="nofollow noreferrer">this place</a> where you could find the answer to this question.</p>
<p>The main idea is to use <code>tf.data.Iterator.from_structure()</code> instead... | python|tensorflow|deep-learning|tensorflow-datasets|dropout | 0 |
360,103 | 54,149,384 | How to install Contextily? | <p>This question is written in relation with the answer to <a href="https://stackoverflow.com/a/54100726/4194079">Plotting a map using geopandas and matplotlib</a>.</p>
<p>The main point is that installing (spatial) libraries such as <a href="https://proj4.org/" rel="noreferrer">Proj.4</a> or <a href="https://github.c... | <p><strong>Using Anaconda / conda</strong></p>
<p>If you are using the <a href="https://www.anaconda.com/download" rel="noreferrer">Anaconda distribution</a> or in general the conda package manager (which I recommend for installing the python geo stack), it should suffice to install contextily with:</p>
<pre><code>co... | python-3.x|geopandas|contextily | 13 |
360,104 | 54,017,588 | How to get comma separated values in new column pandas dataframe? | <p>I have the following dataframe</p>
<pre><code> import pandas as pd
def remove_dup(string):
temp=string.split(',')
temp=[x.strip() for x in temp]
return ','.join(set(temp))
compnaies = ['Microsoft', 'Google', 'Amazon', 'Microsoft', 'Facebook', 'Google','Google']
products = ['OS', 'Search', 'E-comm',... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> with <code>expand=True</code>, change columns names and new column <code>uniquecount</code> is count by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand... | python|pandas | 2 |
360,105 | 53,862,068 | How to fix finding same dates in two columns and join rows of two dataframes according to same date | <p>I am trying to combine two dataframes, i have date column in df1 and date1 column in df2. i want to compare first value of df1 column date to all value of df2 date1 column if similar value found in date2 just combine similar value row of df2 to the first row of df1 date. then do same for second value of df1 date col... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging</a></p>
<pre><code>import pandas as pd
all_df = pd.merge(df1, df2, left_on='date1'... | python|python-3.x|pandas | 0 |
360,106 | 54,085,939 | Why are my pandas DataFrame columns Dataframes too, not Series? | <p><strong>Update at end</strong>
<strong>Update 2 at end</strong></p>
<p>I read from here:
<a href="https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column">get list from pandas dataframe column</a></p>
<blockquote>
<p>Pandas DataFrame columns are Pandas Series when you pull them out</p>... | <p>I think you have duplicated columns names, so if want select <code>Series</code> get <code>DataFrame</code>:</p>
<pre><code>df = pd.DataFrame([[1,2],[4,5], [7,8]], index=list('aab')).T
print (df)
a a b
0 1 4 7
1 2 5 8
print (df['a'])
a a
0 1 4
1 2 5
print (type(df['a']))
<class 'pandas.core.... | python|pandas|dataframe | 6 |
360,107 | 54,212,960 | Convert nested DataFrame with sorted unique values, to a nested Dictionary in Python | <p>I'm trying to take a nested DataFrame and convert it to a nested Dictionary.</p>
<p>Here is my original DataFrame with the following unique values:</p>
<p>input: <code>df.head(5)</code></p>
<p>output:</p>
<pre><code> reviewerName title reviewerRatings
0 Charles ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with lambda function for <code>dictionaries</code> per <code>reviewerName</code> and then output <code>Series</code> convert by <a href="http://pandas.pydata.org/pandas... | python|pandas|dictionary|dataframe|nested | 4 |
360,108 | 54,173,838 | Numpy modify multiple values 2D array using slicing | <p>I want to change some values in a numpy 2D array, based on the values of another array. The rows of the submatrix are selected using boolean slicing and the columns are selected by using integer slicing.</p>
<p>Here is some example code:</p>
<pre><code>import numpy as np
a = np.array([
[0, 0, 1, 0, 0],
[1... | <p>You could use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.argwhere.html" rel="nofollow noreferrer">argwhere</a>:</p>
<pre><code>rows = np.argwhere(a[:, 3] == 0)
cols = [2, 3, 4]
b[rows, cols] = 2 # Replace the values with 2
print(b)
</code></pre>
<p><strong>Output<... | python|arrays|numpy|slice|submatrix | 3 |
360,109 | 53,984,680 | Convert matrix to tuples | <p>Say I generate a sequence of values, tile them by the range provided and then increment each value in each row by that current row ID, then mask some values outside of a desired range like below:</p>
<pre><code>>>> range = 5
>>> matrix = np.arange(-5, 10, 1)
>>> matrix = np.tile(matrix, (... | <p>Playing around with your <code>matrix</code> I produced this:</p>
<pre><code>In [50]: np.stack((matrix.compressed(), np.where(~matrix.mask)[0]),1)
Out[50]:
array([[ 0, 0],
[ 1, 0],
[ 2, 0],
[ 3, 0],
[ 4, 0],
[ 5, 0],
[ 6, 0],
[ 7, 0],
[ 8, 0],
... | python|arrays|numpy | 0 |
360,110 | 53,827,938 | Searching multiple substrings in a column of strings and return substring category | <p>I have two dataframes as follows:</p>
<pre><code>df1 = pd.DataFrame({"id":["01", "02", "03", "04", "05", "06"],
"string":["This is a cat",
"That is a dog",
"Those are birds",
"These are bats",
... | <pre><code># Modified your data a bit.
df1 = pd.DataFrame({"id":["01", "02", "03", "04", "05", "06", "07"],
"string":["This is a cat",
"That is a dog",
"Those are birds",
"These are bats",
... | python|string|pandas|dataframe|lookup | 4 |
360,111 | 54,125,907 | Keras: How to create a sparsely connected layer? | <p>I want to have neural network where the nodes in the input layer just connected to some nodes in the hidden layer. In small it should look similar to this:
<img src="https://i.stack.imgur.com/tFGBJ.png" alt="example"></p>
<p>My original problem has 9180 input nodes and 230 hidden nodes (these numbers refer to the b... | <p>You can multiply the weights of the layer with the binary mask, that you have.
For example, let's suppose, you have 4 inputs and 3 outputs. Now you have weight matrix between these layer is of dim (4,3). And you also have mask matrix, which tell about connection. Now point-wise multiply both matrix, and you are goo... | tensorflow|keras|neural-network|keras-layer | 1 |
360,112 | 53,852,357 | concatenate all strings of one variable in python | <p>I have a dataframe with a variable called var1 and var2. There are 5 observations, as follows:</p>
<p>var1 var2</p>
<pre><code>1 hello there
2 my name is
3 john and
4 i am 30 years
5 old
</code></pre>
<p>is there a way to concatenate each observation string in var2 into one string? for example, create a... | <p>Yes, use <code>join</code>:</p>
<pre><code>s = ' '.join(df['var2'])
print (s)
hello there my name is john and i am 30 years old
</code></pre> | python|string|pandas|list|string-concatenation | 2 |
360,113 | 54,169,506 | Sort parts of 2D numpy array | <p>So I have a numpy array A of dimensions (8760,12). Basically all the hours of 12 years. I need to sort each month (730 hours) in each year in the array. I haven't found any way to do it inside the array. So my solution was to take out each month, sort it and then create the entire 2d array again. I was thinking of d... | <p>You can use python indexes and assignment instead of concatenate if you create the empty array first.</p>
<pre><code>A = np.random.randint(0,99,(8760,12))
total=np.zeros([8760,12])
for j in range(12):
for i in range (12):
total[730*i:730*(i+1),j] = np.sort(A[730*i:730*(i+1),j])
</code></pre>
<p>If you ... | python|numpy | 2 |
360,114 | 53,977,169 | how to merge tow pandas series to table | <p>I have 2 Pandas series:</p>
<p>First</p>
<pre><code>A 91
P 7
F 281
M 54
</code></pre>
<p>Second</p>
<pre><code>A 107
P 3
F 290
M 51
</code></pre>
<p>I want to combine them so they look like this:</p>
<pre><code>A 91 107
P 7 3
F 281 290
M 54 51
</code></pre>
<p>With null if index not found.</p> | <p>You can use a simple <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> for this:</p>
<pre><code>pd.concat([df1,df2], axis = 1)
First Second
A 91 107
P 7 3
F 281 290
M 54 51
</code>... | python|pandas|merge | 2 |
360,115 | 54,136,094 | Finding efficiently which points are in each pixel with Python | <p>I have a 2D grid representing a set of pixels. For each pixel, I have the coordinates of the top left corner.</p>
<p>I also have a very long list of randomly distributed 2D points. I am looking for an efficient way of finding the indices of the points present in each pixel.</p>
<p>For the moment I have the followi... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.floor.html" rel="nofollow noreferrer"><code>np.floor</code></a> to vectorize the whole operation and avoid looping entirely, as long as the separation between pixels is even in each direction. For your simple case, where <code>xgrid</cod... | python|numpy | 1 |
360,116 | 53,996,793 | How do I figure out the value which is greater than certain threshold in a matrix? | <p>Assume that I have a matrix:</p>
<pre><code>a = [[4,7,2],[0,1,4],[4,5,6]]
</code></pre>
<p>And I want to get</p>
<pre><code>b = [0, 1]
c = [[2],[0,1]]
</code></pre>
<ul>
<li><code>b = [0,1]</code> because the inner lists of <code>a</code> at position <code>0</code> and <code>1</code> contain values that are sma... | <p>You can leverate <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer"><code>enumerate(iterable[,startingvalue])</code></a> which gives you the index <em>and</em> the value of the thing you iterate over:</p>
<pre><code>a = [[4,7,2],[0,1,4],[4,5,6]]
thresh = 3
b = [] # coll... | python|python-3.x|numpy|for-loop|enumerate | 0 |
360,117 | 53,977,062 | panda select columns different frames | <p>I have a bunch of csv files. Each csv file comes from a machine and the epoch time of each csv file is roughly the same.</p>
<p>I want to accomplish a few things:</p>
<p>1) plot the same column of each of the machines. So I can make a comparison between the machines of some metric on that machine. E.g. memory usag... | <p>By merging on position you mean on row position? Because in that case you could just concatenate them as such:</p>
<p><code>df = pd.concat([fr1, fr2], axis=1)</code></p>
<p>Not sure if I understand your sum question properly, but because you have all data in one frame you could now add columns together as such:</p... | pandas | 1 |
360,118 | 53,827,838 | Fill NaN in both columns either values present | <p>I have a two columns in df, sometimes it has NaN in either one column, sometimes in both columns. I want to fill NaN with same value if any one of the columns values present.</p>
<p>For ex,
Input:</p>
<pre><code> col1 col2
0 3.375000 4.075000
1 2.450000 1.567100
2 NaN NaN
3 3.248083 ... | <p>You don't have to transpose, you can specify an axis:</p>
<pre><code>df.ffill(1).bfill(1)
col1 col2
0 3.375000 4.075000
1 2.450000 1.567100
2 NaN NaN
3 3.248083 3.248083
4 2.335725 2.335725
5 2.150000 3.218750
</code></pre>
<p>If you have multiple columns, but don't want to touch... | python|pandas | 4 |
360,119 | 54,049,139 | Mask lower triangluar portion of pandas DataFrame | <p>This is a dataframe output I'm generating, which is a 5 x 5 correlation matrix.</p>
<pre><code> A B C D E
A 1.00000 -0.277360 0.653920 -0.479600 0.513890
B -0.27736 1.000000 -0.790648 0.885801 -0.482763
C 0.65392 -0.790648 1.000000 -0.876451 0.672148
... | <p>Check with <code>tril_indices</code></p>
<pre><code>df.values[np.tril_indices(len(df))]=np.nan
df
A B C D E
A NaN -0.27736 0.653920 -0.479600 0.513890
B NaN NaN -0.790648 0.885801 -0.482763
C NaN NaN NaN -0.876451 0.672148
D NaN NaN NaN NaN -0.... | python|pandas|dataframe | 2 |
360,120 | 53,841,951 | Difference between aliasing,deep copy ,shallow copy pertaining to numpy | <pre><code>from numpy import *
arr1=array([1,2,3])
arr2=arr1 #aliasing
arr3=arr1.view() #shallow copy
arr4=arr1.copy() #deep copy
id(arr1) #120638624
id(arr2) #120638624
id(arr3) #120639004
id(arr4) #123894390
</code></pre>
<p>I know about shallow copy and deep copy as in C,C++ but what is it which is happening in pyt... | <p>You have aliasing and deep copy right (though copying array values in a <code>for</code>-loop is not usually considered a good way to do it).</p>
<p>On the other hand, a Numpy <code>view</code> is not a pointer. It's a much heavier duty thing, and a proper object instance in it's own right. Conceptually, it's the c... | python-3.x|numpy|deep-copy|shallow-copy | 0 |
360,121 | 54,126,451 | What does axis=[1,2,3] mean in K.sum in keras backend? | <p>I'm trying to implement a custom loss function for my CNN model. I found an <a href="https://github.com/rekon/Smoke-semantic-segmentation/blob/linknet-implementation/LinkNet.ipynb" rel="noreferrer">IPython notebook</a> that has implemented a custom loss function named Dice, just as follows:</p>
<pre><code>from kera... | <p>Just like in numpy, you can define the axis along you want to perform a certain operation. For example, for a 4d array, we can sum along a specific axis like this</p>
<pre><code>>>> a = np.arange(150).reshape((2, 3, 5, 5))
>>> a.sum(axis=0).shape
(3, 5, 5)
>>> a.sum(axis=0, keepdims=True)... | python|tensorflow|keras|conv-neural-network | 4 |
360,122 | 53,959,258 | Appending cell Value in Pandas for emptied cell in row | <p>I have following table, based on the <code>St_date</code>, <code>En_date</code> is empty or not we have to merge the data in <code>Des</code> with upcoming rows till we find <code>notnull</code></p>
<pre><code> St_date En_date Des Ch Deb Cr Tot
0 01/06/18 01/06/18 CS... | <p>You can do it like that (Note that I consider St_Date <code>Nan</code> like an empty string in the answer below):</p>
<pre><code># Add a field containing previous index if St_date is empty
df["idx"] = df.apply(lambda x: x.name if x.St_date!='' else None, axis=1).ffill()
df
</code></pre>
<p>Should return this :</p>... | python|pandas|dataframe|cell | 1 |
360,123 | 53,850,204 | Speeding up iterator operation in python | <pre><code>[pd.Series(pd.date_range(row[1].START_DATE, row[1].END_DATE)) for row in df[['START_DATE', 'END_DATE']].iterrows()]
</code></pre>
<p>Is there anyway to speed up this operation?
Basically for a given date range I am creating all rows of dates in between them.</p> | <p>Instead of creating a <code>pd.Series</code> on each iteration, do:</p>
<pre><code>[pd.date_range(row[1].START_DATE, row[1].END_DATE))
for row in df[['START_DATE', 'END_DATE']].iterrows()]
</code></pre>
<p>And create a dataframe from the result. Here's an example:</p>
<pre><code>df = pd.DataFrame([
{'start_... | python|pandas|numpy | 2 |
360,124 | 54,082,018 | How to read a column from a csv file in python | <p>I currently am using pandas to read from a csv file but I'm trying to remove the index column, Name and dtype from my output </p>
<pre><code>import pandas as pd
df = pd.read_csv('C:/Users/Book2.csv')
list = [df['Column1']]
print (list)
</code></pre>
<p>Output:</p>
<pre><code>[0 ST
1 VC
2 ST
3 ST
4 ... | <p>This kind of depends on what you are trying to do. If you just want the values, you can add <code>list = df.values</code> to the list. If you are trying to append to a list, you can do <code>list += df.values</code> after initializing <code>list</code>.</p> | python|pandas|csv | 0 |
360,125 | 54,093,037 | Sort a column based on the sorting of a column from another pandas data frame | <p>I have a dataframe like this:</p>
<pre><code> df1:
col1 col2
P 1
Q 3
M 2
</code></pre>
<p>I have another dataframe:</p>
<pre><code>df2:
col1 col2
Q 1
M 3
P 9
</code></pre>
<p>I want to sort the col1 of df2 based on the order of col1 of df1. So the f... | <p>You could set <code>col1</code> as index in <code>df2</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> and index the dataframe using <code>df1.col11</code> with <a href="https://pandas.pydata.org/pandas-... | python|pandas|dataframe | 3 |
360,126 | 53,978,707 | More efficient solution to find longest series based on boolean in NumPy ndArray | <p>I search my ndArray to find longest series based on True values. Is there an option to find longest series without looping through array?</p>
<p>I've already wrote my own solution with numpy.nonzero, but there is probably better one.</p>
<pre><code>import numpy as np
arr = np.array([[[1,2,3,4,5],
[... | <p>Here is a numpy solution which avoids explicit loops based on <a href="https://stackoverflow.com/questions/1066758/find-length-of-sequences-of-identical-values-in-a-numpy-array-run-length-encodi">this previous question.</a></p>
<p>I'm assuming the boolean array is named <code>a</code>. Essentially we find the indic... | python|numpy|multidimensional-array | 0 |
360,127 | 54,049,599 | Pandas series/df update with set_index() | <p>Considering the below dataframes:</p>
<pre><code>df = pd.DataFrame([["11","1", "2"], ["12","1", "2"], ["13","3", "4"]],
columns=["ix","a", "b"])
df1 = pd.DataFrame([["22","8", "9"], ["12","10", "11"], ["23","12", "13"]],
columns=["ix","c", "b"])
df df1
... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>update</code></a> modifies the calling DataFrame in-place. From the docs:</p>
<blockquote>
<p>Modify in place using non-NA values from another DataFrame.</p>
<p>Aligns on indices. The... | python-3.x|pandas|dataframe | 1 |
360,128 | 54,045,129 | I have 8 years of daily data. I want to graph all values per day of the week, per weeks in a year and per month in a year. How do I do that? | <p>I want to be able to visualize my data points per days of the week, per weeks in a year and per months. I was able to visualize my data per year. But when I adjust the code for Monthly and weekly, the x-axis remains as per year. </p>
<p>I have 8 years of hospital records. My data is organized into 2 columns. Column... | <p>So, as I had assumed, this was easy given the dates were available.</p>
<p>So first create new columns denoting which week, year and month a date belong to. For that you need to set Dates as index and parse_dates while reading the csv:</p>
<pre><code>data=pd.read_csv('Data 3.csv',index_col='Dates',parse_dates=True... | python|pandas|matplotlib|data-visualization | 3 |
360,129 | 54,103,605 | Python Pandas sum with multiple conditions | <p>Below is my sample data:</p>
<pre><code> Customer Document Date Clearing Date Invoice_Amount
0 A 09/13/2016 11/04/2016 2,007,324
1 A 04/18/2016 07/11/2016 631,714
2 A 09/13/2016 09/16/2016 4,000,000
3 A 07/11/2017... | <p>Going by your example:</p>
<pre><code>import pandas as pd
# read in csv (save as csv or read in using pd.read_excel)
df = pd.read_csv('file.csv')
# to datetime just in case
df['Doc_Date'] = pd.to_datetime(df['Doc_Date'])
df['Exp_Date'] = pd.to_datetime(df['Exp_Date'])
df['Overdue'] = df['Doc_Date'] - df['Exp_Date']... | python|pandas | 0 |
360,130 | 53,854,785 | How can access to data with multiindex in column python | <p>I have a dataframe with data from yahoo finance. This dataframe has two index column.</p>
<pre><code>data = pdr.get_data_yahoo(['AAPL','AMAZ'],start = datetime.date(2018, 1, 1) ,end= datetime.date.today())
data
</code></pre>
<p>How can I do to get a subdataframe only with the information of AAPL since the DATA d... | <p>I found the solution!</p>
<pre><code>data.xs('AAPL',axis=1, level=1)
Open High Low Close Adj Close Volume
Date
2018-11-30 180.289993 180.330002 177.029999 178.580002 178.580002 39531500
2018-12-03 184.460007 184.940002 181.210007 184.820007 184.820007 40802500
2018-12-... | python|pandas|yahoo | 3 |
360,131 | 54,042,246 | How to send a numpy array to armadillo (C++) and return a numpy array from armadillo | <p>I want to send a numpy array to a Armadillo (C++) and output a numpy array from the C++ program. I didn't find any tutorials online for this. Can someone give me pointers on how to do this ? </p> | <p>You can rely on cython and the numpy c interface for the data conversion. There are different projects that implement this including <a href="https://sourceforge.net/projects/armanpy/" rel="nofollow noreferrer">armanpy</a>, a library for conversion between numpy and armadillo, or <a href="https://www.mlpack.org/doc/... | python|c++|numpy|armadillo | 2 |
360,132 | 38,462,642 | Updating Panel slice | <p>I need to update a panel slice with some values retreated from a dataframe. Even if I don't get back any error it doesn't work. What it's wrong ?</p>
<pre><code>df = pd.DataFrame(np.random.rand(10, 4),
columns=['sd', 'ed', 'sbc', 'ssd'],
index=np.arange(2000, 201... | <p>You're getting into some semi-complicated dimensional issues.</p>
<p>Let's break down your assignment line a bit.</p>
<pre><code>siPanel.loc[:, [0], [0]] = df.loc[:, ['sbc']]
</code></pre>
<p><code>df.loc[:, ['sbc']]</code> is a dataframe with a shape of <code>10 x 1</code>. <code>:</code> gave it the <code>10</... | pandas|slice|panel|pandas-loc | 0 |
360,133 | 38,433,069 | numpy multiply arrays with different shapes | <p>I have an array <code>A</code> of shape <code>(w,h) = 3000,2000</code>
and another array <code>B</code> of shape <code>d = 100</code></p>
<p>I want to multiply each value of <code>A</code> by <code>B</code>, and get the result in the form of an array <code>C</code> of shape <code>(w,h,d) = 3000,2000,100</code></p>
... | <p>Use numpy <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="noreferrer">broadcast</a>.</p>
<p>Try this </p>
<pre><code>from numpy.random import rand
a = rand(4,5)
b = rand(6)
c = a[...,None] * b
print (c.shape)
</code></pre>
<p>Or equivelently</p>
<pre><code>c = a.reshape(4,5,1)*b
</co... | arrays|python-2.7|numpy | 5 |
360,134 | 38,296,949 | python pandas binning numerical range | <p>I have a reqt., where I want to bin a numeric value</p>
<pre><code>If the student marks is
b/w 0-50 (incl 50) then assign the level column value = "L"
b/w 50-75(incl. 75) then assign the level column value ="M"
>75 then assign the level column value ="H"
</code></pre>
<p>Here is what I have got </p>
<pre><co... | <p>Try this: </p>
<pre><code> bins = [0,50,75,101] or bins = [0,50,75,np.inf]
</code></pre> | python|pandas|numeric|binning | 2 |
360,135 | 38,499,890 | How to use pandas apply function on all columns of some rows of data frame | <p>I have a <code>dataframe</code>. I want to replace values of all columns of some rows to a default value. Is there a way to do this via <code>pandas apply</code> function</p>
<p>Here is the dataframe</p>
<pre><code>import pandas as pd
temp=pd.DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7],'c':['p','q','r','s','t',... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> to create a boolean mask and use <code>loc</code> to set the rows that meet the condition to the desired new value:</p>
<pre><code>In [37]:
temp.loc[temp['c'].isin(mylist),['a','b']] = 0
... | python|pandas|data-manipulation | 3 |
360,136 | 38,167,388 | AttributeError: 'Tensor' object has no attribute 'shape' | <p>Stack trace</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 6, in <module>
connection.start_socket(8089, callback=handler.message_processor)
File "/mnt/d/workspace/SketchRecognitionWithTensorFlow/src/main/python/connection/python_socket_server.py", line 13, in start_socket
p... | <p>Since there is no accepted answer and I'm myself coming from Google:<br>
Credit goes to mrry with <a href="https://stackoverflow.com/questions/38666040/tensorflow-attributeerror-tensor-object-has-no-attribute-shape">this answer</a>, which reads:<br>
Since TensorFlow 1.0, <code>tf.Tensor</code> now has a <a href="htt... | python|tensorflow | 3 |
360,137 | 38,467,838 | Distributed Tensorflow Errors/ | <p>When running a distributed tensorflow (TF v0.9.0rc0) set up, I start up 3 parameter servers and then 6 workers. The parameter servers seem to be fine, giving the message <code>Started server with target: grpc://localhost:2222</code>. But the workers give other errors (below) that I have questions about.</p>
<p>It... | <p>I figured out what my problem was. </p>
<p><strong>TL;DR</strong>: The chief needs to know about <em>all</em> the variables in order to initialize them <em>all</em>. Non-chief workers can't create their own variables.</p>
<p>I was converting an old program where all workers had a few independent variables, but n... | tensorflow|distributed | 1 |
360,138 | 38,369,291 | Maybe a bug in DataFrame.reindex ? | <p>python 2.7.11</p>
<p>pandas 0.18.1 </p>
<p>when i try to do like this:</p>
<pre><code>idx = pd.MultiIndex.from_product([['Ia','Ib'],['i1','i2','i3']])
df = pd.DataFrame({'A':['c','b','b','a','b','a'],'B':[10,-20,50,40,None,50],'C':[100,50,-30,-50,70,40]},index=idx)
print df.reindex(index=['Ib','Ia'],columns=['B',... | <p>To answer the question: No, that is not OK! And it's not a bug... really.</p>
<p>Consider the dataframe <code>df</code>:</p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(4, 2),
pd.MultiIndex.from_product([['a', 'b'], ['C', 'D']]),
['One', 'Two'])
df
</code></pre>
<p><a hr... | python|pandas | 0 |
360,139 | 38,286,269 | Tensorflow variable Reuse in rnn module | <p>I'm very perplexed by TF variable reuse. For method rnn, I'm able to find this line of code:</p>
<pre><code> if time > 0: vs.get_variable_scope().reuse_variables()
</code></pre>
<p>However, for <code>dynamic_rnn</code> (the method I need to use), I do not find any reuse_variable line of code, or reuse=True.</... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn" rel="nofollow noreferrer">dynamic_rnn</a> function has a parameter called scope. So you should create your own scope (using <code>with tf.variable_scope('scope_name', reuse=True)</code>) and set it when calling <code>dynamic_rnn</code> functi... | tensorflow | 1 |
360,140 | 38,468,549 | how to convert pandas series to tuple of index and value | <p>I'm looking for an efficient way to convert a series to a tuple of its index with its values.</p>
<pre><code>s = pd.Series([1, 2, 3], ['a', 'b', 'c'])
</code></pre>
<p>I want an array, list, series, some iterable:</p>
<pre><code>[(1, 'a'), (2, 'b'), (3, 'c')]
</code></pre> | <p>Well it seems simply <code>zip(s,s.index)</code> works too!</p>
<p>For Python-3.x, we need to wrap it with <code>list</code> -</p>
<pre><code>list(zip(s,s.index))
</code></pre>
<p>To get a tuple of tuples, use <code>tuple()</code> : <code>tuple(zip(s,s.index))</code>.</p>
<p>Sample run -</p>
<pre><code>In [8]: ... | python|pandas|series|iterable | 59 |
360,141 | 38,259,423 | How to use the columns to divide the DataFrame into groups? | <p>At first, DataFrame likes this:</p>
<p><a href="https://i.stack.imgur.com/Lsiwn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lsiwn.png" alt="first"></a></p>
<p>I wish to change it like this:</p>
<p><a href="https://i.stack.imgur.com/nTBx9.png" rel="nofollow noreferrer"><img src="https://i.st... | <p>there is a module called <strong>itertools</strong>.
use the <strong>groupby</strong> method on the specific column.</p>
<p>(if not helpful let me know)</p> | python|pandas | 0 |
360,142 | 38,145,404 | right join with pandas | <pre><code>stores = [[232, '2016-02-05 04:30:00', 'Test User', 1],
[332, '2016-02-06 04:30:00', 'Test User', 2],
[432, '2016-02-07 04:30:00', 'Test User', 3],
[532, '2016-02-08 04:30:00', 'Test User', 4],
[632, '2016-02-09 04:30:00', 'Test User', 5]]
visits = pd.DataFrame(data=s... | <p>You want a left join, not right join. Then it works:</p>
<pre><code> auditor scene product amount
store visit
232 2016-02-05 04:30:00 Test User 1 1551.0 2.0
332 2016-02-06 04:30:00 Test User 2 NaN NaN
432... | python|pandas|dataframe | 0 |
360,143 | 38,224,985 | Scale rows of 3D-tensor | <p>I have an <code>n</code>-by-<code>3</code>-by-<code>3</code> numpy array <code>A</code> and an <code>n</code>-by-<code>3</code> numpy array <code>B</code>. I'd now like to multiply every <em>row</em> of every one of the <code>n</code> <code>3</code>-by-<code>3</code> matrices with the corresponding scalar in <code>B... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> to let the elementwise multiplication happen in a vectorized manner after extending <code>B</code> to <code>3D</code> after adding a singleton dimension at the end with <code>np.newa... | python|arrays|numpy|matrix | 2 |
360,144 | 38,253,700 | Tensorflow: global_step not incremented; hence exponentialDecay not working | <p>I'm trying to learn Tensorflow, and I wanted to use the Tensorflow's cifar10 tutorial framework and train it on top of mnist (combining two tutorials). </p>
<p>In cifar10.py's train method:</p>
<pre><code>cifar10.train(total_loss, global_step):
lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE, ... | <p>You are passing an argument called <code>global_step</code> to <code>mnist.training</code>, AND also creating a variable called <code>global_step</code> in <code>mnist.training</code>. The one used for tracking the <code>exponential_decay</code> is the variable that is passed in, but the one that is actually increme... | python|tensorflow | 5 |
360,145 | 38,286,717 | TensorFlow - regularization with L2 loss, how to apply to all weights, not just last one? | <p>I am playing with a ANN which is part of Udacity DeepLearning course.</p>
<p>I have an assignment which involves introducing generalization to the network with one hidden ReLU layer using L2 loss. I wonder how to properly introduce it so that ALL weights are penalized, not only weights of the output layer.</p>
<p>... | <p>A shorter and scalable way of doing this would be ;</p>
<pre><code>vars = tf.trainable_variables()
lossL2 = tf.add_n([ tf.nn.l2_loss(v) for v in vars ]) * 0.001
</code></pre>
<p>This basically sums the l2_loss of all your trainable variables. You could also make a dictionary where you specify only the variables... | machine-learning|neural-network|tensorflow|deep-learning|regularized | 106 |
360,146 | 38,319,898 | tensorflow neural net with continuous / floating point output? | <p>I'm trying to create a simple neural net in tensorflow that learns some simple relationship between inputs and outputs (for example, y=-x) where the inputs and outputs are floating point values (meaning, no softmax used on the output).</p>
<p>I feel like this should be pretty easy to do, but I must be messing up so... | <p>Your loss should be the squared difference of output and true value:</p>
<pre><code>loss = tf.reduce_mean(tf.square(expected - net))
</code></pre>
<p>This way the network learns to optimize this loss and make the output closer to the real result. Cross entropy should only be used for output values between 0 and 1 ... | tensorflow | 11 |
360,147 | 38,415,854 | How to make TensorFlow use more available CPU | <p><strong>How can I fully utilize each of my EC2 cores?</strong></p>
<p>I'm using a c4.4xlarge AWS Ubuntu EC2 instance and TensorFlow to build a large convoluted neural network. nproc says that my EC2 instance has 16 cores. When I run my convnet training code, the top utility says that I'm only using 400% CPU. I was ... | <p>Several things you can try:</p>
<h1>Increase the number of threads</h1>
<p>You already tried changing the <code>intra_op_parallelism_threads</code>. Depending on your network it can also make sense to increase the <code>inter_op_parallelism_threads</code>. From the <a href="https://stackoverflow.com/questions/3775... | amazon-web-services|amazon-ec2|tensorflow | 8 |
360,148 | 38,227,775 | Slicing and Setting Values in Pandas, with a composite of position and labels | <p>I want to set a value in a specific cell in a <code>pandas dataFrame</code>.</p>
<p>I know which position the row is in (I can even get the row by using <code>df.iloc[i]</code>, for example), and I know the name of the column, but I can't work out how to select the cell so that I can set a value to it.</p>
<pre><c... | <p>You can use <code>ix</code> to set a specific cell:</p>
<pre><code>In [209]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df
Out[209]:
a b c
0 1.366340 1.643899 -0.264142
1 0.052825 0.363385 0.024520
2 0.526718 -0.230459 1.481025
3 1.068833 -0.558976 0.812986
4 0... | pandas | 2 |
360,149 | 38,253,939 | Numpy FFT issue when shifting data along vertical axis | <p>I want to find the relationship between the y-axis of my data and the vertical axis of my FFT (amplitude). To do this I am testing how the amplitude of my FFT changes when I change the y-axis of my data. For example, I plotted sin(t) from 0 to 2*pi and took the FFT using Numpy's FFT package and got a frequency of ap... | <p>Try this, it will convince you that all is working well:</p>
<pre><code>t = np.linspace(0, 2*math.pi, 10000)
y2 = np.sin(200*t) + 1
</code></pre>
<p>The 1 adds a very strong peak at 0 frequency. But the sin peak is also there.</p> | python|numpy|fft|trigonometry|amplitude | 0 |
360,150 | 66,300,268 | StringLookup equivalent for tensorflow v2.1.0 | <p>I am trying to build one recommendation model similar to this <a href="https://www.tensorflow.org/recommenders/examples/basic_retrieval" rel="nofollow noreferrer">example</a>. But this example uses Tensorflow v2.4.0 and for my work, I need to use v2.1.0. It seems that the <code>StringLookUp</code> layer does not exi... | <p>You can use <a href="https://www.tensorflow.org/versions/r2.1/api_docs/python/tf/strings/to_hash_bucket_strong" rel="nofollow noreferrer">tf.strings.to_hash_bucket_strong</a> to hash your strings to indices, as long as you don't care about the mapping order.</p>
<p><strong>Example</strong>:</p>
<pre><code>import ten... | tensorflow|tensorflow2.0 | 1 |
360,151 | 65,972,673 | How to iterate over DataFrame columns and drop NaN value | <p>I have this example DataFrame:</p>
<pre><code>d = {'col1': [1, 2, np.NaN], 'col2': [3, np.NaN, 4], 'col3': [np.NaN, 5, 6]}
df = pd.DataFrame(data=d)
</code></pre>
<p><a href="https://i.stack.imgur.com/NKLwR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NKLwR.png" alt="enter image description her... | <p>You can do this in one line using 'dropna' of pandas. No need to iterate. Already asked here: <a href="https://stackoverflow.com/questions/43119503/how-to-remove-blanks-nas-from-dataframe-and-shift-the-values-up">How to remove blanks/NA's from dataframe and shift the values up</a></p>
<pre><code>df = df.apply(la... | python|pandas|numpy | 1 |
360,152 | 66,118,695 | pandas dataframe venn diagram | <p>I have 3 dataframes, and for one exercise I had to join them together and get the common rows based on country column</p>
<p><a href="https://i.stack.imgur.com/Pw987.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pw987.png" alt="enter image description here" /></a></p>
<p>However for this new exe... | <p>If you are looking for the number of rows, then you can try doing an outer join like so</p>
<pre><code>merged_df = pd.merge(Energy, GDP, on="Country", how='outer')
</code></pre>
<p>Do the outer join just the same as you did for your inner join, and then obtain the difference between the outer join and the ... | python|pandas | 1 |
360,153 | 66,117,835 | Pandas: Create different dataframes from an unique multiIndex dataframe | <p>I would like to know how to pass from a multiindex dataframe like this:</p>
<pre><code>A B
col1 col2 col1 col2
1 2 12 21
3 1 2 0
</code></pre>
<p>To two separated dfs. df_A:</p>
<pre><code> col1 col2
1 2
3 1
</code></pre>
<p>df_B:</p>
<pr... | <p>I think here is better use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>DataFrame.xs</code></a> for selecting by first level:</p>
<pre><code>print (df.xs('A', axis=1, level=0))
col1 col2
0 1 2
1 3 1
</code></pre>
<p>W... | python-3.x|pandas | 1 |
360,154 | 66,207,609 | NotImplementedError: Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. T | <p>tensorflow version 2.3.1
numpy version 1.20</p>
<p>below the code</p>
<pre><code># define model
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
</code></pre>
<p>we got</p>
<blockquote>
<p>NotImplementedErro... | <p>I solved with numpy downgrade to 1.18.5</p>
<pre><code>pip install -U numpy==1.18.5
</code></pre> | python|numpy|tensorflow | 44 |
360,155 | 66,027,394 | Alternative method to json_normalize that flattens lists within dictionaries | <p>I have a dictionary which contains a list that needs to be flattened to level 0.</p>
<p>Currently, I am using <code>json_normalize</code>, however, after some days of research I found out that it does not deal with lists and keeps it in one column.</p>
<p>Is there an alternative method to flatten the dictionary as w... | <p>You can systematically break it down using <code>json_normalise()</code> <code>explode()</code> and <code>apply(pd.Series)</code></p>
<pre><code>js = {'_id': 1,
'active': False,
'labelId': [6422],
'level': [{'active': True,
'level': 3,
'actions': [{'active': True, 'description': 'Testing.'}]}]}
df = pd.jso... | python|json|pandas|dictionary | 2 |
360,156 | 65,953,130 | how to compare a pair of words in pandas? | <p>I have 2 columns like this:</p>
<pre><code>col count
(A,B) 19
(C,D) 18
(E,F) 10
(B,A) 9
(D,C) 80
</code></pre>
<p>I want this:</p>
<p>for each pair <code>(pair1,pair2)</code> in <code>col</code> if <code>(pair2,pair1)</code> exist, select one with higher <code>count</code></p>
<p><code>output</cod... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.idxmax</code></a> for get maximal <code>count</code> index values grouping by sorted and converted lists to tuples:</p>
<pre><code>g = df['... | pandas|dataframe|count | 0 |
360,157 | 66,102,516 | How can I assign the words from a specific column as a label to a new dataframe | <p>Hi Friend I'm new here ,</p>
<p>Make a matrix from most repeated words in specific column <code>A</code> and add to my data frame with names of selected column as label.</p>
<h3>What I have:</h3>
<pre><code>raw_data={"A":["This is yellow","That is green","These are orange",&qu... | <p>So I changed your code a little, your step 3 looks like this:</p>
<pre><code># 3- Countung the seprated words and the frequency of repetation
df_word_count=pd.DataFrame(df.A.str.split(' ').explode().value_counts()).reset_index().rename({'index':"A","A":"Count"},axis=1)
display(df_word_c... | python|pandas|dataframe | 1 |
360,158 | 66,297,283 | OpenCV Error: Assertion failed (nimages > 0 && nimages == (int)imagePoints1.tot ........ line3106 | <p><strong>OLD:</strong> Trying the OpenCV tutorial for camera calibration.<br />
<strong>Kindly look for part two right after "EDIT" below the the first python code section</strong></p>
<p>I receive this error:</p>
<pre><code>OpenCV Error: Assertion failed (nimages > 0 && nimages == (int)imagePoin... | <p>This is the solution for the first part related to<br />
<code>cameraCalibration()</code><br />
<em>Never mind, I think I found it. There is an issue with the arguments I provided for the function calibrateCamera()</em></p>
<p>Now there is a new problem on 21/feb/2021 under EDIT.</p>
<p>Solution for EDIT, problem pa... | python|python-2.7|numpy|opencv | 0 |
360,159 | 66,279,506 | Pandas Dataframes - Search an integer from one data frame in a string column in another dataframe | <p>I have two data frames:</p>
<p><strong>DF1</strong></p>
<pre><code> cid dt tm id distance
2 ed032f716995 2021-01-22 16:42:48 43 21.420561
3 16e2fd96f9ca 2021-01-23 23:19:43 539 198.359355
102 cf092e68fa82 2021-01-22 09:03:14 8 39.599627
104 833... | <p>One way is split the <code>cluster</code>, <code>explode</code> it and map:</p>
<pre><code>to_map = (df2.assign(cluster_i=df2.cluster.str.split(','))
.explode('cluster_i').dropna()
.set_index('cluster_i')['cluster']
)
df1['cluster'] = df1['id'].astype(str).map(to_map)
</code></pre>
<p>Output:</p>
<pre><code... | python|pandas|dataframe | 3 |
360,160 | 66,161,384 | Combining columns and joining non-missing values in Pandas | <p>Imagine that I have a single Dataframe as such:</p>
<pre><code>df = pd.DataFrame([[1,2,3,None],[1,2,3,None],[1,2,3,None],[None,2,3,1]], columns=["A","B","C","AA"])
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</t... | <p>You could try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine_first.html" rel="nofollow noreferrer">combine_first</a>:</p>
<pre><code>In [8]: df.assign(A=df.A.combine_first(df.AA)).drop(columns='AA')
Out[8]:
A B C
0 1.0 2 3
1 1.0 2 3
2 1.0 2 3
3 1.0 2 3
<... | python|pandas | 1 |
360,161 | 66,317,323 | How to find r2score of my PyTorch model for regression | <p>I have a UNet model. I'm trying for a regression model since, in my output, I have different floating values for each pixel. In order to check the r2score, I tried to put the below code in the <code>model class</code>, training_step, validation_step, and test_step.</p>
<p><code>from pytorch_lightning.metrics.functio... | <p>The issue is that the function accepts 1D or 2D tensors, but your tensor is 4D (B x C x H x W). So to use the function you should reshape it:</p>
<pre><code>r2 = r2score(pred.view(pred.shape[1], -1), y.view(y.shape[1], -1))
</code></pre> | python|pytorch|pytorch-lightning | 2 |
360,162 | 66,190,989 | Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 | <p>I have a model which was trained on MNIST, but when I put in a handmade sample of an image it raises ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 1)</p>
<p>I already checked the input of the model it is ... | <p>You need an extra dimension in here, <code>arr.reshape(1, 784)</code>. Here is the full working code</p>
<pre><code>(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# train set / data
x_train = x_train.reshape(-1, 28*28)
x_train = x_train.astype('float32') / 255
# train set / target
y_t... | python|tensorflow|machine-learning|keras|deep-learning | 8 |
360,163 | 65,957,535 | simplity construction of sparse (transition) matrix | <p>I am constructing a transition matrix from a <code>n1 x n2 x ... x nN x nN</code> array. For concreteness let <code>N = 3</code>, e.g.,</p>
<pre><code>import numpy as np
# example with N = 3
n1, n2, n3 = 3, 2, 5
dim = (n1, n2, n3)
arr = np.random.random_sample(dim + (n3,))
</code></pre>
<p>Here <code>arr</code> con... | <p>One approach that beats the one posted in the OP. Not sure if it's the most efficient.</p>
<pre><code>import numpy as np
from scipy import sparse
# get col and row indices
idx = np.arange(np.prod(dim))
row = idx.repeat(dim[-1])
col = idx.reshape(-1, dim[-1]).repeat(dim[-1], axis=0).ravel()
# get the data
data = ar... | python|numpy|multidimensional-array|sparse-matrix|simplify | 0 |
360,164 | 65,974,957 | How to groupby and plot the aggregated values | <p>This is the dataframe that I'm using: <a href="https://www.kaggle.com/spscientist/students-performance-in-exams" rel="nofollow noreferrer">https://www.kaggle.com/spscientist/students-performance-in-exams</a></p>
<p>It contains the following columns (That I want to use):</p>
<ol>
<li>Race/Ethnicity (String: GROUP A, ... | <ul>
<li>Addressing <em>I would prefer to use seaborn</em>: <code>seaborn</code> is just a high-level API for <code>matplotlib</code>.</li>
<li>There are two easy ways to generate the desired grouped plot
<ol>
<li>Groupby and plot the grouped dataframe
<ul>
<li>The OP already has grouped the dataframe, but should not h... | python|pandas|matplotlib|seaborn | 1 |
360,165 | 66,179,008 | new dataframe column based on dictionary and str.contains() | <p>I want to create a new dataframe <code>df</code> column <code>new_col</code>, placing the key value <code>k</code> of a dictionary <code>my_dict</code>, if some specific column <code>col_1</code> contains some string that is inside the dictionary values <code>v</code>, ( using regex character + join() ).</p>
<p>I di... | <p><code>str.contains()</code> works with a regular expression but it is meant for a column wise operation. You need to go through all the values of your dictionary. I don't know if there's a easy way to use it, maybe something like:</p>
<pre><code>mx = [df.col_1.str.contains('|'.join(v)) for v in my_dict.values()]
df[... | python|pandas | 1 |
360,166 | 66,242,070 | Filter nan values out of rows in pandas | <p>I am working on a calculator to determine what to feed your fish as a fun project to learn python, pandas, and numpy.</p>
<p>My data is organized like this:</p>
<p><a href="https://i.stack.imgur.com/ZzCiE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZzCiE.png" alt="enter image description here" /></a></... | <p>You can use masks in pandas:</p>
<pre><code>food = 'Amphipods'
mask = df[food].notnull()
result_set = df[mask]
</code></pre>
<p><code>df[food].notnull()</code> returns a mask (a Series of boolean values indicating if the condition is met for each row), and you can use that mask to filter the real DF using <code>df[m... | python|pandas|dataframe|data-manipulation | 6 |
360,167 | 66,092,967 | How does NumPy seed its random number generators if no seed is provided? | <p>For example, suppose I call <code>numpy.random.uniform(0, 1, 10)</code> without calling any of the seed-related functions. NumPy must be using some default seed, but I couldn't find it in the documentation. How does NumPy seed its random numbers when no seed is specified?</p> | <p>For NumPy's legacy <code>numpy.random.*</code> functions, including <code>numpy.random.uniform</code>, a global <a href="https://github.com/numpy/numpy/blob/master/numpy/random/mtrand.pyx#L4566" rel="nofollow noreferrer"><code>RandomState</code> object initialized with no arguments</a> is used. Because a seed isn't ... | python|numpy|random|random-seed | 6 |
360,168 | 66,064,517 | ffill pandas dataframe with a strict fill limit | <p>This questions builds upon the old question: <a href="https://stackoverflow.com/questions/45343153/pandas-ffill-bfill-for-specific-amount-of-observation">pandas ffill/bfill for specific amount of observation</a></p>
<p>Where the following answer is given.</p>
<pre><code>df['filled'] = df.groupby("id")[&quo... | <p>In your case, you can check the consecutive <code>NaN</code> blocks and mask the filled column:</p>
<pre><code>forward=2
# we groupby on `.notna().cumsum()` to find block sizes
# then compare to number of forward limit
valid_blocks = (df.groupby([df['indicator'].notna().cumsum(), 'id'])
['id'].tra... | python|pandas|dataframe|nan | 2 |
360,169 | 65,991,325 | How can I solve attribute error for Pandas : "AttributeError: module 'pandas' has no attribute 'StringDtype'"? | <p>pd.Series(["a","b","c"], dtype=pd.StringDtype())</p>
<p>AttributeError: module 'pandas' has no attribute 'StringDtype'</p> | <p>You need upgrade pandas, because <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.StringDtype.html" rel="nofollow noreferrer"><code>pandas.StringDtype</code></a> is implemented in pandas 1.0.0+:</p>
<blockquote>
<p>class pandas.StringDtype<br />
Extension dtype for string data.</p>
</blockq... | python|pandas|error-handling|jupyter|attributeerror | 1 |
360,170 | 66,093,323 | (Conceptual question) Tensorflow dataset... why use it? | <p>I'm taking a MOOC on Tensorflow 2 and in the class the assignments insist that we need to use tf datasets; however, it seems like all the hoops you have to jump through to do anything with datasets means that everything is way more difficult than using a Pandas dataframe, or a NumPy array... So why use it?</p> | <p>The things you mention are generally meant for small data, when a dataset can all fit in RAM (which is usually a few GB).</p>
<p>In practice, datasets are often much bigger than that. One way of dealing with this is to store the dataset on a hard drive. There are other more complicated storage solutions. TF DataSets... | python|tensorflow|conceptual | 0 |
360,171 | 66,141,720 | Having trouble with GridSearchCV.fit displaying TypeError | <p>I was wondering if anyone could help me understand this error.</p>
<pre><code>---> 83 return array(a, dtype, copy=False, order=order)
84
85
ValueError: setting an array element with a sequence.
</code></pre>
<p>It seems to have stemmed from another error listed below.</p>
<pre><code>TypeError: only siz... | <p>Answered as per my edits. Would appreciate if someone could provide me some wisdom as to why this happened.</p> | python|pandas|numpy|scikit-learn | 0 |
360,172 | 66,052,748 | How to change the string type list to a list type and then drop nan elements | <p>I have a unique problem. I am facing two issues here. First, my list is a string type, not list type. Then, some of the elements in the list are nan. I want to drop them.</p>
<p>My code:</p>
<pre><code>x = '[1.4,2.3,nan]'
print(type(x)) # prints str
x = eval(x) # with this I want to drop end quotes, convert it to li... | <p>Please don't use <code>eval</code> for anything if you're not acutely aware how unsafe it is. Instead, properly parse your input.</p>
<pre><code>import math
s = '[1.4,2.3,nan]'
x = [float(n) for n in s.lstrip('[').rstrip(']').split(',')]
x = [n for n in x if not math.isnan(n)]
</code></pre> | python|list|numpy | 2 |
360,173 | 66,327,011 | Pythons Pandas - Converting Str object values in a column to Float | <p>I have a dataframe that have currently contain a column of income data stored as strings (Object). I want to convert it to float however when I used:</p>
<p>df['Income'] = pd.to_numeric(df['Income_2016'], errors='coerce')</p>
<p>and used df.dtypes, the Income is float64 however when I displayed the df the previous v... | <p>Gotta remove the comma</p>
<p>Try:</p>
<pre><code>df['Income'] = pd.to_numeric(df['Income_2016'].str.replace(',',''), errors='coerce')
</code></pre> | python|pandas|dataframe | 2 |
360,174 | 66,113,738 | Filtering Negative values less than certain value in pandas | <p>I have two columns "Esc1" and "Esc2". I want to apply a "where" condition such that if the difference between esc1 and esc2 is less than -30 then "yes less than -30" else "No".</p>
<p>I used the following code,</p>
<pre><code>np.where((df['Esc1']-df['Esc2']<-30),&... | <pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame()
df['Esc1'] = np.arange(10)
df['Esc2'] = np.arange(10, 50, 4)
df['diff'] = df['Esc1'] - df['Esc2']
pd.cut(df['diff'], bins=[-np.inf, -30, np.inf], labels=['yes less than -30', 'no'])
</code></pre> | pandas|dataframe|numpy | 0 |
360,175 | 66,263,382 | ValueError: logits and labels must have the same shape ((None, 1) vs (None, 10000)) when trying to classify IMDB reviews | <p>I'm trying to classify IMDB movie reviews with binary classification using Keras. The following is the code I used.</p>
<pre class="lang-py prettyprint-override"><code>from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(16,activation="relu",input_shape=(100... | <p>As stated <code>ValueError</code>, you're trying to compute the loss of between shape <code>((None, 1)</code> vs <code>(None, 10000))</code>. It would be clear if you posted or refer the training set of IMDB. Try with in-built IMDB data set from <code>keras</code>.</p>
<pre><code>import numpy as np
from tensorflow i... | python|tensorflow|machine-learning|keras|logits | 1 |
360,176 | 66,271,160 | df.to_markdown, ValueError: could not convert string to float: '1,000'. Disabling number parsing with disable_numparse=True | <p>so this worked perfectly with python 3.9 but I had to downgrade to 3.8 and now this line of code no longer works. I dont understand why it thinks its a float.</p>
<pre><code>df = pd.DataFrame({'col 1': [f"{1000:,d}"], 'col 2': [f"{2000:,d}"]}).to_markdown(index=False)
print(df)
</code></pre>
<p>... | <p>Just pass <code>disable_numparse=True</code> to <code>to_markdown()</code></p>
<pre><code>df = pd.DataFrame({'col 1': [f"{1000:,d}"], 'col 2': [f"{2000:,d}"]}).to_markdown(disable_numparse=True)
df
>>>
'| | col 1 | col 2 |\n|:---|:--------|:--------|\n| 0 | 1,000 | 2,000 |'
... | python|python-3.x|pandas | 1 |
360,177 | 66,158,107 | Python Tensorflow - EOFError: marshal data too short | <p>I've been facing this issue for a while now. Whenever I import TensorFlow, I get the following:</p>
<pre class="lang-py prettyprint-override"><code>
2021-02-11 21:05:05.855414: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10... | <p>I had this issue when trying to import a model trained on TensorFlow v2.6.0 into an environment using TensorFlow v2.7.0. I downgraded the environment back to v2.6.0, which has resolved the error.</p> | python|python-3.x|tensorflow | 1 |
360,178 | 66,201,625 | Convert /reshape a dataset from 'wide to long' format and convert the time column into time format for time-series analysis | <p>I have a dataset with 7 columns - <code>level</code>,<code>Time_30</code>,<code>Time_60</code>,<code>Time_90</code>,<code>Time_120</code>,<code>Time_150</code> and <code>Time_180</code></p>
<p>My main goal is to do a time-series anomaly detection using cell count in a 30-minute interval.</p>
<p>I want to do the foll... | <p>I made a few small edits to your sample dataframe based on my comment above:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'level':['A','B','C','D','E'],
'Time_30':[1993.05,1999.45, 2001.11, 2007.39, 2219.77],
'Time_60':[2123.15,2299.59, 2339.19, 2443.37, 2553.15],
'Time_90':[2323.56,... | python|pandas|plot|time-series | 1 |
360,179 | 66,236,018 | How to serialize a dataframe in django? Is there a way to return dataframe along with queryset in django? | <p>What I'm trying to do here is get a query based on users' choices like date, group, and symbol.</p>
<p>I would like to convert this queryset to a data frame using django_pandas.</p>
<p>I tried to convert the data frame generated to JSON object but it gives some errors like:</p>
<blockquote>
<p>TypeError: Object of t... | <p>You write:</p>
<pre><code>df = df.set_index(['org','id'],inplace=True)
</code></pre>
<p>The <code>inplace=True</code> means you want to make the changes to the same object, due to this the method returns nothing causing <code>None</code> to be stored in <code>df</code>. Change the line to either of the below:</p>
<p... | python|django|pandas|dataframe|django-pandas | 0 |
360,180 | 66,114,119 | Pandas : Removing duplicates row based on some conditions | <p>I have one dataset in excel which looks as below.</p>
<pre><code>name,role,org
abc,admin,123
abc,agent,123
abc,end-user,123
abc,admin,124
abc,admin,123
bcd,admin,125
abc,admin,126
abc,agent,127
abc,agent,123
abc,end-user,130
abc,end-user,130
abc,agent,123
bc,agent,123
bc,admin,123
vcf,end-user,123
</code></pre>
<p>I... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> with <a href="http://andas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></... | python|pandas | 0 |
360,181 | 65,976,348 | Can't merge dataframes because of index type mismatch | <p>I have loaded some data from CSV files into two dataframes, <code>X</code> and <code>Y</code> that I intend to perform some analysis on. After cleaning them up a bit I can see that the indexes of my dataframes appear to match (they're just sequential numbers), except one has index with type <code>object</code> and t... | <p>So I've realised what I've done and it was pretty dumb. I should have written</p>
<pre class="lang-py prettyprint-override"><code>X.index = X.index.astype('int64')
</code></pre>
<p>instead of just</p>
<pre class="lang-py prettyprint-override"><code>X.index.astype('int64')
</code></pre>
<p>Oh well, the more you know.... | python|pandas|dataframe | 0 |
360,182 | 66,200,818 | displaying columns names of dataFrame in python | <p>I have an xlsx file having about 100 columns. When I use <code>df.columns</code> function then it display some of the first and some last columns but not all of them. I want to display(print) all of the column name (headings) though for loop. How can I do it?</p> | <pre><code>for col in df.columns:
print(col)
</code></pre> | python|pandas|dataframe | 2 |
360,183 | 65,961,877 | Pandas: How to preserve _id when parsing nested list? | <p>I am trying to access a nested list within a pandas DataFrame, but when I do so I somehow cannot hold on to the <code>_id</code>. But the <code>_id</code> is needed for later processing.</p>
<p>The DataFrame looks like, where coordinates is a list of floats:</p>
<pre><code> _id coordinates... | <p>you can save the id too in the dictionary using this code:</p>
<pre><code>c_dict.append({'id':data['_id'],'lat': c[0], 'lng': c[1]})
</code></pre> | python|pandas|dataframe | 2 |
360,184 | 66,021,355 | Universal Sentence Encoder tensorflowjs optimize performance using webworker | <p>I am using the following code to initiate Webworker which creates embeddings using Universal Sentence Encoder</p>
<pre><code>const initEmbeddingWorker = (filePath) => {
let worker = new Worker(filePath);
worker.postMessage({init: 'init'})
worker.onmessage = (e) => {
worker.terminate();
... | <p>Using 10 webworkers means that the machine used to run it has at least 11 cores. Why this assumption ? (number of webworker + main thread )</p>
<p>To leverage the use of webworker to the best, each webworker should be run on a different core. What happens when there are more workers than cores ? Well the program won... | javascript|web-worker|tensorflow.js|word-embedding | 0 |
360,185 | 65,950,732 | tf.tape.gradient() returns None for my numerical function model | <p>I'm trying to use <code>tf.GradientTape()</code>.
But the problem is <code>tape.gradient</code>returns <code>None</code>, so that the error output (<code>TypeError : unsupported operand type(s) for *: 'float' and 'NoneType'</code>) popped up.
As you can see in my code, <code>dloss_dparams = tape.gradient(Cost, [XX,Y... | <p>You are doing calculations outside of TensorFlow. That will result in a gradient of None, see the guide : <a href="https://www.tensorflow.org/guide/autodiff#getting_a_gradient_of_none" rel="nofollow noreferrer">Getting a gradient of None</a></p>
<blockquote>
<p>The tape can't record the gradient path if the calculat... | python|tensorflow|gradienttape | 2 |
360,186 | 66,201,980 | Creating a dataframe by repeating each column a certain number of times | <p>I need to turn the following dataframe:</p>
<pre><code>ID | A | B | C | D | E |
1 | 3 | 1 | 2 | 1 | 0 |
2 | 0 | 1 | 2 | 5 | 2 |
3 | 2 | 2 | 5 | 3 | 10 |
</code></pre>
<p>into one that has each column name as the new value, repeated the number of times specified in the value. So, three r... | <p>One way using <code>pandas.DataFrame.columns.repeat</code>:</p>
<pre><code>df.apply(df.columns.repeat, axis=1).explode()
</code></pre>
<p>Output:</p>
<pre><code>ID
1 A
1 A
1 A
1 B
1 C
1 C
1 D
2 B
...
3 E
3 E
3 E
dtype: object
</code></pre> | python|python-3.x|pandas|dataframe | 5 |
360,187 | 66,291,970 | How to plot 2D density clouds so that multiple clouds can be combined? | <p>I'd like to make some similar plots like my first figure. I already used the code below to get the second figure. How can I obtain the same effect as the first figure?</p>
<pre><code>from scipy import stats
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#read data
df=pd.read_excel('plot.xlsx... | <p>You can use seaborn's <a href="https://seaborn.pydata.org/generated/seaborn.kdeplot.html#seaborn.kdeplot" rel="nofollow noreferrer"><code>kdeplot()</code></a> with <code>fill=True</code> and setting a threshold (<code>thresh=</code> between 0 and 1) which cuts off the lowest densities. You may need to experiment to ... | python|pandas|numpy|matplotlib | 1 |
360,188 | 66,126,912 | using panda dataframe, how to calculate average of sequence of data in csv log file? | <p>I want to take the average of sequence of repeating rows. For example,</p>
<pre><code>a 0.1
b 0.2
c 0.2
a 0.4
b 0.1
c 0.3
a 0.4
b 0.5
c 0.3
</code></pre>
<p>and I want the following output.</p>
<pre><code>a 0.300
b 0.267
c 0.267
</code></pre>
<p>I was able to read csv file as dataframe and so... | <p>Complementing @Quang Hoang and your commentary, you could either deal with other columns applying some kind of aggregation too, like:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col0':["a", "b", "c", "a", "b", "c", "a", "b", ... | python|pandas|dataframe|csv | 1 |
360,189 | 66,336,989 | plot no longer works after upgrade | <p>I recently upgraded pandas to 1.1.5, using Python 3.6.4 and I can no longer plot any charts with a datetime index column.</p>
<p>See the below example where I import a time series from a csv file. I have also tried registering matplotlib converters in case this was the issue. I get the error message shown below. Inc... | <p>The older version of matplotlib (2.1.2) is out of date and no longer compatible with the newer version of pandas (1.1.5). An upgrade to matplotlib 3.3.4 solves this issue - as discussed in the comments.</p> | pandas|datetime|matplotlib|plot | 1 |
360,190 | 66,166,875 | Count value between datetime and NaT | <p>I have two python pandas dataframes, in simplified form they look like this:</p>
<p>DF1</p>
<pre><code>+---------+---------+------+-------+
| Date_in | Date_out| Group| Item |
+---------+---------+------+-------+
| 1991-08 | 2000-08 | A | A1 |
| 1992-08 | NaT | A | A2 |
| 1997-02 | NaT | B | ... | <p>You can first convert all datetimes and replace missing <code>NaT</code> to today date in first step:</p>
<pre><code>df2['Date'] = pd.to_datetime(df2['Date'])
df1['Date_in'] = pd.to_datetime(df1['Date_in'])
df1['Date_out'] = pd.to_datetime(df1['Date_out']).fillna(pd.to_datetime('now').normalize())
print (df1)
... | pandas|dataframe|map-function | 1 |
360,191 | 66,268,742 | How do you prevent memory usage to explode when using Keras in a loop | <p>My problem seems to be very common.</p>
<p>I am doing some reinforcement learning using a vanilla policy gradient method. The environment is just a simple one period game where the state and action spaces are the real line. The agent is a neural network with two output heads that I build manually using dense layers ... | <p>You could try restarting the backend by calling</p>
<pre><code>reset_tensorflow_keras_backend()
</code></pre>
<p>after each model estimation, where the function is defined like:</p>
<pre><code>def reset_tensorflow_keras_backend():
# to be further investigated, but this seems to be enough
import tensorflow as... | python|tensorflow|keras|reinforcement-learning | 1 |
360,192 | 66,296,157 | How do you read a txt file (from SQLCMD) into Pandas DataFrame? | <p>I've Google searched but haven't found a way to parse SQL txt file outputs and import as Pandas DataFrame. I have, within the cmd line:</p>
<pre><code>sqlcmd -S server_name -E -Q "select top 10 * from table_name" -o "test.txt"
</code></pre>
<p>This produces a text file, which isn't exactly the b... | <p>Add error handeling to the read_csv:</p>
<pre><code>df_test = pd.read_csv('test.txt', sep = ' ', errors='coerce')
</code></pre> | sql|sql-server|python-3.x|pandas|sqlcmd | 0 |
360,193 | 52,556,305 | how to print quantiles using plotnine in python | <p>I have the following <code>dataframe</code>:</p>
<pre><code>import pandas as pd
import numpy as np
from plotnine import *
df = pd.DataFrame.from_dict({'variable': {0: 'intercept', 1: 'intercept', 2: 'intercept', 3: 'intercept', 4: 'intercept', 5: 'intercept', 6: 'intercept', 7: 'intercept', 8: 'intercept', 9: 'int... | <p>Here's one way to achieve your desired output:</p>
<ul>
<li>Add <code>stat_boxplot(geom='errorbar', coef=1)</code> to draw vertical ticks at exactly 1.0 times the IQR, i.e., at the 25th and 75th percentiles</li>
<li>Pass <code>nudge_x = 0.12</code> to <code>geom_text</code></li>
</ul>
<p>New code:</p>
<pre><code>... | python|python-3.x|pandas|plotnine | 1 |
360,194 | 52,580,111 | How do I set the column width when using pandas.DataFrame.to_html? | <p>I have read <a href="https://pandas.pydata.org/pandas-docs/stable/style.html" rel="noreferrer">this</a>, but I am still confused about how I set the column width when using <code>pandas.DataFrame.to_html</code>.</p>
<pre><code>import datetime
import pandas
data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, d... | <p>Try this: </p>
<pre><code>import datetime
import pandas
data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1},
'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4},
'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9,... | python|pandas | 26 |
360,195 | 52,698,784 | Pandas DataFrame to multidimensional NumPy Array | <p>I have a Dataframe which I want to transform into a multidimensional array using one of the columns as the 3rd dimension.<br>
As an example:</p>
<pre><code>df = pd.DataFrame({
'id': [1, 2, 2, 3, 3, 3],
'date': np.random.randint(1, 6, 6),
'value1': [11, 12, 13, 14, 15, 16],
'value2': [21, 22, 23, 24, 25, 26]
})
</c... | <p><strong>Approach #1</strong></p>
<p>Here's one vectorized approach after sorting <code>id</code> col with <code>df.sort_values('id', inplace=True)</code> as suggested by @Yannis in comments -</p>
<pre><code>count_id = df.id.value_counts().sort_index().values
mask = count_id[:,None] > np.arange(count_id.max())
... | python|arrays|pandas|numpy|transform | 11 |
360,196 | 52,829,787 | Keras Custom generator issue when evaluating the model | <p>I am training a CNN LSTM model using Keras, and after the training was done, I tried to evaluate the model on the testing data like I did when I fine-tuned my CNN, however an error appears this time.</p>
<p>After training was done, I tried to following piece of code to evaluate on my testing set:</p>
<pre><code>x,... | <p>I think this line is the problem</p>
<pre><code>x, y = zip(*(testgenerator[i] for i in range(len(testgenerator))))
</code></pre>
<p>because you call <code>len</code> on generator object.
The solution may be if you just create some counter, increment it and use it as index in <code>testgenerator[i]</code></p> | python|tensorflow|keras|generator | 1 |
360,197 | 52,578,749 | How to filter observation based on the next period observation in DataFrame | <p>DATA::</p>
<pre><code>Unnamed: 0 gvkey date CUSIP conm tic cik PERMNO COMNAM
0
0 1001 1983 00016510 A & M FOOD SERVICES INC AMFD. 723576.0 10015 NaN
1
1 1001 1983 00016510 A & M FOOD SERVICES INC AMFD. 723576.0 10015 A & M FOOD SERVICES INC
2
5 1001 1984 00016510 A & M FOOD SERVICES INC... | <h3>Ensure you use consistent mask indices</h3>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isna.html" rel="nofollow noreferrer"><code>pd.Series.isna</code></a> returns a <strong>series</strong>, not a Boolean value. Importantly, since you apply a filter first via <code>df[df['date... | python|pandas|dataframe | 0 |
360,198 | 52,539,318 | How to drop duplicates where there is no data? | <p>I Have a df that looks like this: </p>
<pre><code>Id column2 column3 column4 column5
1 1 1 1 nan
1 1 nan nan 1
</code></pre>
<p>I want to drop duplicates via the <code>Id</code> column and keep data in columns where the <code>Id</code> has data, ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><code>GroupBy.last</code></a> for return last not NaNs values per groups:</p>
<pre><code>df1 = df.groupby('Id', as_index=False).last()
print (df1)
Id column2 column3 column4 col... | python|python-3.x|pandas|duplicates | 1 |
360,199 | 52,751,456 | How to map object types into int64 in pandas.DataFrame with a large data set | <p>I have data for machine learning study, but I stuck with those string features. I want to map <code>them(object</code>) into <code>number(int64)</code>. </p>
<p>For example, in feature <code>workclass</code>, make a <code>map(dict)</code> as <code>{'private':0,'State-gov':1, etc}</code>.</p>
<p>So, how can I deal ... | <pre><code>pandas.get_dummies(data)
</code></pre>
<p>It will convert categorical variable into dummy/indicator variables.</p>
<p>or in your case</p>
<pre><code>pandas.get_dummies(df_trainFeautres['workclass'])
</code></pre> | python|pandas|machine-learning | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.