Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use df.loc and if condtions in python pandas to delete a row

Tags:

python

pandas

I wanted to use the if condition and df.loc[..] to compare two values in the same column.
If the previous value is higher then next one, I want to delete the complete row.

This what I tried and my example:

import pandas as pd
data = [('cycle',[1,1,2,2,3,3,4,4]),
         ('A',[0.1,0.5,0.2,0.6,0.15,0.43,0.13,0.59]),
         ('B',[ 500, 600, 510,580,512,575,499,598]),
         ('time',[0.0,0.2,0.5,0.4,0.6,0.7,0.5,0.8]),]
df = pd.DataFrame.from_items(data)

df = df.drop(df.loc[i,'time']<df.loc[i-1,'time'].index)
print(df)

and I got the following error :

TypeError: '<' not supported between instances of 'numpy.ndarray' and 'str'

Help is very is much appreciated

like image 384
sulphur Avatar asked Mar 22 '19 17:03

sulphur


1 Answers

Try this:

df.drop(df.loc[df.time< df.time.shift()].index, inplace=True)
like image 200
Loochie Avatar answered Nov 05 '22 17:11

Loochie