简体   繁体   English

如何计算 Pandas DataFrame 中行之间的百分比增长?

[英]How to calculate growth in percentage between rows in a Pandas DataFrame?

I have a data-frame such as:我有一个数据框,例如:

 A   B(int64)
 1   100
 2   150
 3   200

now I need to calculate the growth rate and set it as an additional column such as:现在我需要计算增长率并将其设置为附加列,例如:

 A    C
 1   naN
 2   50%
 3  33.33%

how can I achieve that?我怎样才能做到这一点? Thank you so much for your help!非常感谢你的帮助!

Use Series.pct_change with multiple by 100 with Series.mul and rounding by Series.round :使用Series.pct_change乘以100Series.mul并通过Series.round四舍五入:

df['C'] = df.B.pct_change().mul(100).round(2)
print (df)
   A    B      C
0  1  100    NaN
1  2  150  50.00
2  3  200  33.33

For percentage add map with format and processing with missing values with NaN != NaN :对于百分比添加map format和处理缺失值与NaN != NaN

df['C'] = df.B.pct_change().mul(100).round(2).map(lambda x: '{0:g}%'.format(x) if x==x else x)
print (df)
   A    B       C
0  1  100     NaN
1  2  150     50%
2  3  200  33.33%

You're looking for pct_change :您正在寻找pct_change

df['B'] = df.B.pct_change().mul(100).round(2)
df['B'] = df.B.where(pd.isna, df.B.astype(str).add('%'))

print(df)

   A       B
0  1     NaN
1  2   50.0%
2  3  33.33%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM