我已经收到了累积数字的数据。有没有一种聪明的方法来逆转数据的积累,这样我就可以逐月地把数据收集起来,而不是叠在一起?你知道吗
输入示例:
Date SalesRep itemA
01-12-2017 X 1
01-12-2017 Y 0
01-12-2017 Z 0
01-01-2018 X 1
01-01-2018 Y 1
01-01-2018 Z 0
01-02-2018 X 1
01-02-2018 Y 1
01-02-2018 Z 1
期望输出:
Date SalesRep itemA
01-12-2017 X 1
01-12-2017 Y 0
01-12-2017 Z 0
01-01-2018 X 0
01-01-2018 Y 1
01-01-2018 Z 0
01-02-2018 X 0
01-02-2018 Y 0
01-02-2018 Z 1
我使用的脚本,我从论坛重用。你知道吗
import pandas as pd
df = pd.read_excel('File.xlsx')
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.sort_values('Date', ascending=False) # This now sorts in date order
cum_columns = ['itemA']
result = df.merge(
df.groupby('SalesRep')[cum_columns].diff(),
left_index=True, right_index=True, suffixes=['', '_uncum']
).fillna({'{}_uncum'.format(cum_column): df[cum_column] for cum_column in cum_columns})
print(result)
因为对于最后一个月,每个值都是1,那么其余的月份都是0。如何更改脚本以处理我的案例?你知道吗
编辑
使用JohnE-answer我得到错误请看:
Date SalesRep ItemA itemA_diff
2018-08-01 00:00:00 John 1 1
2018-07-01 00:00:00 John 1 0
2018-06-01 00:00:00 John 0 -1
2018-05-01 00:00:00 John 0 0
2018-04-01 00:00:00 John 0 0
2018-03-01 00:00:00 John 0 0
2018-02-01 00:00:00 John 0 0
2018-01-01 00:00:00 John 0 0
2017-12-01 00:00:00 John 0 0
2017-11-01 00:00:00 John 0 0
2017-10-01 00:00:00 John 0 0
我应该去
Date SalesRep ItemA itemA_diff
2018-08-01 00:00:00 John 1 0
2018-07-01 00:00:00 John 1 1
2018-06-01 00:00:00 John 0 0
2018-05-01 00:00:00 John 0 0
2018-04-01 00:00:00 John 0 0
2018-03-01 00:00:00 John 0 0
2018-02-01 00:00:00 John 0 0
2018-01-01 00:00:00 John 0 0
2017-12-01 00:00:00 John 0 0
2017-11-01 00:00:00 John 0 0
2017-10-01 00:00:00 John 0 0
应该改变什么?你知道吗
这是组合
groupby
和diff
的一个相当标准的用例,尽管语法可能相当芬尼基(参见下面的注释):结果:
注意事项:
首先按“Date”排序是很重要的,而且您已经根据需要使用
pd.to_datetime
转换为适当的pandas datetime。我不知道为什么,但是“Date”和“itemA”都需要是列而不是索引。(我第一次尝试在索引中使用“Date”时出现了奇怪的错误)
替代方法:以下是@jezrael要求提供的原始答案,可能更快:
相关问题 更多 >
编程相关推荐