Python 减去 Python Dataframe 的累积列

标签 python pandas

我有每日累计金额,我想将其分解为每日值。当然也需要分组。

例如,我想获取此数据框并返回以下结果:

ID    Date            Cum Value
3306  2019-06-01      100.0 
3306  2019-07-01      200.0 
3306  2019-08-01      350.0
4408  2019-06-01      200.0
4408  2019-07-01      375.0
4408  2019-08-01      400.0

ID    Date           Cum Value  Daily Value
3306  2019-06-01      100.0     100.0
3306  2019-07-01      200.0     100.0
3306  2019-08-01      350.0     150.0
4408  2019-06-01      200.0     200.0
4408  2019-07-01      375.0     175.0
4408  2019-08-01      400.0     025.0

我已经尝试过

df['Daily Value'] = df['Cum Value'].sub(df['Cum Value'].shift())
df['Daily Value'].iloc[0] = df['Cum Value'].iloc[0]

最佳答案

您可能需要groupby+difffillna:

df['Daily Value']=df.groupby('ID')['Cum Value'].diff().fillna(df['Cum Value'])
print(df)
<小时/>
     ID        Date  Cum Value  Daily Value
0  3306  2019-06-01      100.0        100.0
1  3306  2019-07-01      200.0        100.0
2  3306  2019-08-01      350.0        150.0
3  4408  2019-06-01      200.0        200.0
4  4408  2019-07-01      375.0        175.0
5  4408  2019-08-01      400.0         25.0

关于Python 减去 Python Dataframe 的累积列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59633091/

相关文章:

python - 使用 PyCrypto 解密 AES 和 HMAC

python - 具有不同参数的 Python 中的继承

python - 如果值在 : "The truth value of a Series is ambiguous" 范围内,则选择行

sorting - Pandas 多索引排序

python - 如何根据多个条件对 Pandas 中的时间序列数据帧进行切片?

python - 在 Pandas 数据帧上使用 ttest_ind 时遇到问题

python - Django Response 总是 Chunked with text/html 无法设置 Content-Length

python - 为什么 float() 无法将我的字符串转换为 float ?

python - 检测 Pandas 数据框中的事件

python - del运算符如何在python中的列表中工作?