gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:58:43 24 4
gpt4 key购买 nike

我有一个数据框,例如:

 A   B(int64)
1 100
2 150
3 200

现在我需要计算增长率并将其设置为附加列,例如:

 A    C
1 naN
2 50%
3 33.33%

我怎样才能做到这一点?非常感谢您的帮助!

最佳答案

使用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

对于百分比添加 mapformat 并使用 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%

关于python - 如何计算 Pandas DataFrame 中行之间的百分比增长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58708819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com