I'm working with pandas and dataframe, and I have a simple question:
I have a dataframe (let's call it df
) like this:
index | A | B | C |
---|---|---|---|
0 | 3 | 2 | 5 |
1 | 4 | 7 | 6 |
2 | 2 | 4 | 8 |
i need to make an additional column D
, in with I must have the ratio of the C
Value with the precedent one: first value of the column should be 5/0 (where impossible to divide, NAN or 0 will be good), second value should be 6/5, third value should be 8/6.
I can't manage to make it work. I'm trying to apply lambda function but without success when it comes to use the "previous value". (.shift()
is not working)
df['D'] = df['C'].apply(lambda x:x['C']/ ??? )
Is this the right road, or there is something I am missing?
CodePudding user response:
Use Series.shift
instead of apply
:
df['D'] = df['C'] / df['C'].shift()
# index A B C D
# 0 3 2 5 NaN
# 1 4 7 6 1.200000
# 2 2 4 8 1.333333
Optionally chain Series.fillna
if you want 0 instead of NaN:
df['D'] = df['C'].div(df['C'].shift()).fillna(0)
# index A B C D
# 0 3 2 5 0.000000
# 1 4 7 6 1.200000
# 2 2 4 8 1.333333