python - Create new column in pandas dataframe by calculation from previous index columns -
hi new , learning pandas data analysis. have 2 columns data
a b 1 2 2 3 3 4 4 5 i want create third column c result calculated column b , subtracting upper value current 1 , dividing current.
a b c 1 2 2 3 0.33 3 4 0.25 4 5 0.2 for example first row value c column empty because there no value above 2 .
0.33 = > 3 - 2 / 3 , 0.25 = > 4 - 3 / 4 , 0.2 = > 5 - 4 / 5 , on i stuck while getting upper value of current column. need how achieve that.
use shift shift column , remaining operations regular ones (sub , div):
df['b'].sub(df['b'].shift()).div(df['b']) out: 0 nan 1 0.333333 2 0.250000 3 0.200000 name: b, dtype: float64 this can done without chaining methods, if prefer.
(df['b'] - df['b'].shift()) / df['b'] out[48]: 0 nan 1 0.333333 2 0.250000 3 0.200000 name: b, dtype: float64
Comments
Post a Comment