Returns a list of boolean values ​​comparing the strings of a list in Pandas

I want to add a new column "y" for True and False in my framework. It will return the true value. If the next row is greater than the previous row of one column. For example, if I have a column named "X"

X  y
1  
2  True
3  True
2  False

      

How do I do this without a loop. How do I solve this problem with the first line y being empty?

+3


source to share


2 answers


df.assign(y=df.X.diff().gt(0))

   X      y
0  1  False
1  2   True
2  3   True
3  2  False

      




If you want to be pedantic and have zero value in the first place

df.assign(y=pd.Series(np.diff(df.X) > 0, df.index[1:]))

   X      y
0  1    NaN
1  2   True
2  3   True
3  2  False

      

+3


source


In [63]: df['y'] = df.X > df.X.shift()

In [64]: df
Out[64]:
   X      y
0  1  False
1  2   True
2  3   True
3  2  False

      



+3


source







All Articles