Python 基于具有相同日期的其他列从2行创建新列
我有这样的数据框Python 基于具有相同日期的其他列从2行创建新列,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有这样的数据框 date item_id type amount 4538 2019-04-28 00:00:00+00:00 12 2 1050.200000 4539 2019-04-28 00:00:00+00:00 12 1 56.130000 4544 2019-04-29 00:00:00+00:00 12 2 30.588000 4545 2019
date item_id type amount
4538 2019-04-28 00:00:00+00:00 12 2 1050.200000
4539 2019-04-28 00:00:00+00:00 12 1 56.130000
4544 2019-04-29 00:00:00+00:00 12 2 30.588000
4545 2019-04-29 00:00:00+00:00 12 1 52.250000
4550 2019-04-30 00:00:00+00:00 12 2 27.010000
4551 2019-04-30 00:00:00+00:00 12 1 45.832910
4556 2019-05-01 00:00:00+00:00 12 2 22.040000
4557 2019-05-01 00:00:00+00:00 12 1 3756.617900
我想合并两行中日期和金额相同的数据,类型为1的行的金额值将被分配到名为“buy_amount”的新列中,类型2将位于“sell_amount”列中,并省略“type”、“item_id”和第一个索引列,如下所示
date buy_amount sell_amount
2019-04-28 00:00:00+00:00 56.130000 1050.200000
2019-04-29 00:00:00+00:00 52.250000 30.588000
2019-04-30 00:00:00+00:00 45.832910 27.010000
2019-05-01 00:00:00+00:00 3756.617900 22.040000
您可以在此处使用pivot_表并重命名列:
df.pivot_table(index='date', values='amount', columns='type')\
.rename({1:'buy_amount', 2:'sell_amount'}, axis=1)
不要期望人们为您编写代码。通过编辑您的问题,告诉我们您到目前为止做了什么,以及为什么有什么错误(例如,它不起作用)?看看melt,对不起,伙计们。这只是我的第一个问题,我确实试着做了,并在堆栈上搜索了类似的问题,但我什么也没找到。这就是我写这个问题的原因。我会喜欢你们在接下来的问题中提出的建议。谢谢,雷加德斯沃克斯喜欢魅力。谢谢你的帮助很高兴我能帮忙:@Justin
type buy_amount sell_amount
date
2019-04-28 00:00:00+00:00 56.13000 1050.200
2019-04-29 00:00:00+00:00 52.25000 30.588
2019-04-30 00:00:00+00:00 45.83291 27.010
2019-05-01 00:00:00+00:00 3756.61790 22.040