Home > Net >  Compare last value in dataframe
Compare last value in dataframe

Time:08-09

I have this dataframe:

distance

0       0.000000
1       0.001956
2       0.001601
3       0.001601
4       0.003379
      ...   
1236    0.150453
1237    0.152232
1238    0.157923
1239    0.159701
1240    0.159879

Name: close, Length: 1241, dtype: float64

I want to check if last value in dataframe is > 15 or not.

I tried it the following way:

if distance.tail(1) > 15:
   print('bigger > 15')
else:
   print('less < 15')

which gives me the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), 
a.any() or a.all().

How can I get around this?

CodePudding user response:

df.tail returns a Series.

Use df.iloc:

if distance.iloc[-1] > 15:
   print('> 15')
else:
   print('<= 15')

CodePudding user response:

A combination of iloc and indexing -1 will work.

data = pd.DataFrame(['this', 'is', 'a', 'test', 25])
data.columns = ['colname']
data.iloc[-1]['colname']

CodePudding user response:

Well first it looks like you have a pandas Series not DataFrame. But this is how you would do it...

distance.iloc[-1] > 15
  • Related