我想知道是否有什么简单的Python命令或包可以让我轻松地向data.frames添加变量,这些变量是这些变量的“差异”或随时间的变化。
如果我的数据是这样的:
Day Price Good
--- ------- --
1 1 8 apples
2 2 10 apples
3 3 7 apples
4 4 11 apples
5 5 14 apples
6 1 12 oranges
7 2 11 oranges
8 3 9 oranges
9 4 14 oranges
10 5 11 oranges然后,在“第一次差分”价格变量之后,我的数据将如下所示。
Day Price Good P1d
1 1 8 apples NA
2 2 10 apples 2
3 3 7 apples -3
4 4 11 apples 4
5 5 14 apples 3
6 1 12 oranges NA
7 2 11 oranges -1
8 3 9 oranges -2
9 4 14 oranges 5
10 5 11 oranges -3发布于 2021-05-06 04:30:32
使用后跟.diff()的.groupby()
df["P1d"] = df.groupby("Good")["Price"].diff()
print(df)打印:
Day Price Good P1d
1 1 8 apples NaN
2 2 10 apples 2.0
3 3 7 apples -3.0
4 4 11 apples 4.0
5 5 14 apples 3.0
6 1 12 oranges NaN
7 2 11 oranges -1.0
8 3 9 oranges -2.0
9 4 14 oranges 5.0
10 5 11 oranges -3.0https://stackoverflow.com/questions/67408330
复制相似问题