python - 如何使用 Pandas 计算与起始值相比的百分比变化?

标签 python pandas dataframe percentage

我有一个 DataFrame,需要计算公司与年初相比的百分比变化。有什么方法可以使用 pct_change() 或其他方法来执行此任务吗?谢谢!

df 看起来像

security    date        price
IBM         1/1/2016    100
IBM         1/2/2016    102
IBM         1/3/2016    108
AAPL        1/1/2016    1000
AAPL        1/2/2016    980
AAPL        1/3/2016    1050
AAPL        1/4/2016    1070

我想要的结果

security    date        price   change
IBM         1/1/2016    100     NA
IBM         1/2/2016    102     2%
IBM         1/3/2016    108     8%
AAPL        1/1/2016    1000    NA
AAPL        1/2/2016    980     -2%
AAPL        1/3/2016    1050    5%
AAPL        1/4/2016    1070    7%

最佳答案

听起来您正在寻找 expanding_window pct_change() 的版本。这不存在开箱即用的 AFAIK,但您可以自己推出:

df.groupby('security')['price'].apply(lambda x: x.div(x.iloc[0]).subtract(1).mul(100))

关于python - 如何使用 Pandas 计算与起始值相比的百分比变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090498/

相关文章:

Python xpath - 在单个操作中从两个不同的子项获取文本

Python cgi.FieldStorage() 在表单提交时为空

python - 在数据框中查找必须包含列表中至少 2 个元素的行

python - 在 Pandas 数据框中搜索和替换点和逗号

performance - 子集数据帧的最有效方法

python - 是否有任何 python 库可以在漂亮的 ascii 表中输出字典?

python - 如何在 Django Rest Framework 中批量删除实例?

python - pandas:groupby 两列 nunique

python - Pandas 用重复的索引值填充组内缺失的日期和值

r - 计算数据框中自开始以来的月数