看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)某股票最近 5 个交易日的收盘价如下:
[10.0, 10.4, 9.8, 10.2, 10.5]
请用 pandas 的 pct_change() 计算每日涨跌幅,并把结果以带百分比符号的字符串形式(保留 2 位小数)显示。
参考代码如下:
import pandas as pd
df = pd.Series([10.0, 10.4, 9.8, 10.2, 10.5])
df
'''
0 10.0
1 10.4
2 9.8
3 10.2
4 10.5
dtype: float64
'''
df.pct_change().fillna(0)
'''
0 0.000000
1 0.040000
2 -0.057692
3 0.040816
4 0.029412
dtype: float64
'''
(
df.pct_change()
.fillna(0)
.apply(lambda x: f"{x:+.2%}")
)
'''
0 +0.00%
1 +4.00%
2 -5.77%
3 +4.08%
4 +2.94%
dtype: object
'''
查看相关链接中的知识。
(完)
更新时间:2025-08-13 09:10:50 标签:pandas python 股票 涨跌幅