python - Pandas 相对时间轴
问题描述
我有我客户最近八个月的数据,但是这几个月不是同一个月份,只是他们碰巧和我们在一起的最后几个月。每月费用和罚款存储在行中,但我希望过去八个月中的每一个月都是一列。
我有的:
Customer Amount Penalties Month
123 500 200 1/7/2017
123 400 100 1/6/2017
...
213 300 150 1/4/2015
213 200 400 1/3/2015
我想要的是:
Customer Month-8-Amount Month-7-Amount ... Month-1-Amount Month-1-Penalties ...
123 500 400 450 300
213 900 250 300 200
...
我试过的:
df = df.pivot(index=num, columns=[amount,penalties])
我收到了这个错误:
ValueError: all arrays must be same length
有没有一些理想的方法来做到这一点?
解决方案
你可以用unstack
和set_index
# assuming all date is sort properly , then we do cumcount
df['Month']=df.groupby('Customer').cumcount()+1
# slice the most recent 8 one
df=df.loc[df.Month<=8,:]# slice the most recent 8 one
# doing unstack to reshape your df
s=df.set_index(['Customer','Month']).unstack().sort_index(level=1,axis=1)
# flatten multiple index to one
s.columns=s.columns.map('{0[0]}-{0[1]}'.format)
s.add_prefix("Month-")
Out[189]:
Month-Amount-1 Month-Penalties-1 Month-Amount-2 Month-Penalties-2
Customer
123 500 200 400 100
213 300 150 200 400
推荐阅读
- lilypond - 如何创建一个函数来自动创建标题?
- excel - 仅当单元格等于工作表/选项卡名称时,如何复制和粘贴整行?
- apache-kafka - 是否可以减少 min.insync.replicas?
- outlook - 撰写邮件时如何在 Outlook Web App 中显示插件?
- python - Slack API 对话。回复 internal_error
- java - 我如何通过使用字符串来使用可选类
- java - 使用 Scanner 查找未排序数组中的第 N 个最小数字
- python-3.x - 我的 API 返回空白 json,而不是所需的嵌套模式
- c++ - 在我的主应用程序中加载一个 dll 怎么会导致 100 个 CPU 负载?
- firebase - 用于 Tensorflow.js 的 Keras 部署