Python2.7: Change Difference For A Column Value Of Dataframe
I have a dataframe(df) like as following(just example), there are maybe 10 or more dataframes: date a b 0 2010-01-01 12 15 1 2010-01-02
Solution 1:
You can use pct_change
, but first divide value of b
by condition:
dates = ['2010-01-09','2011-01-09']
m = df2['date'].isin(dates)
df2.loc[m, 'b'] = df2['b'] / 10
df2['b_diff'] = df2['b'].pct_change()
print (df2)
date a b b_diff
0 2010-01-01 12 15.0 NaN
1 2010-01-02 13 20.0 0.333333
2 2010-01-03 14 23.0 0.150000
3 2010-01-04 15 24.0 0.043478
4 2010-01-05 16 25.0 0.041667
5 2010-01-08 17 15.0 -0.400000
6 2010-01-09 180 16.0 0.066667
Alternative solution:
dates = ['2010-01-09','2011-01-09']
m = df2['date'].isin(dates)
df2['b'] = df2['b'].mask(m, df2['b'] / 10)
df2['b_diff'] = df2['b'].pct_change()
print (df2)
date a b b_diff
0 2010-01-01 12 15.0 NaN
1 2010-01-02 13 20.0 0.333333
2 2010-01-03 14 23.0 0.150000
3 2010-01-04 15 24.0 0.043478
4 2010-01-05 16 25.0 0.041667
5 2010-01-08 17 15.0 -0.400000
6 2010-01-09 180 16.0 0.066667
Post a Comment for "Python2.7: Change Difference For A Column Value Of Dataframe"