I have the following pandas dataframe (df_merge),
Date Type Counter
0 2021-07-09 T1 1420.000
1 2021-07-09 T2 856.000
2 2021-07-09 T3 1010.000
3 2021-07-09 P 3.408
0 2021-11-30 T1 1775.000
1 2021-11-30 T2 1069.000
2 2021-11-30 T3 1210.000
3 2021-11-30 P 3.408
I want to compute division last two elements of T1 type. 1775.000 / 1420.000 = 1.25
I wrote this code but is there a simpler and shorter way to do this?
df_merge[df_merge['Type']=='T1'].reset_index()['Counter'][1] / df_merge[df_merge['Type']=='T1'].reset_index()['Counter'][0]
Thanks
CodePudding user response:
Filter column with condition in DataFrame.loc:
s = df_merge.loc[df_merge['Type']=='T1', 'Counter']
print (s)
0 1420.0
0 1775.0
Name: Counter, dtype: float64
And then select values by positions in Series.iat - last by -1 and last previous by -2:
out = s.iat[-1] / s.iat[-2]
print (out)
1.25
If need divide second by first:
out = s.iat[1] / s.iat[0]
print (out)
1.25
