gpt4 book ai didi

python - 如何将列移到 Pandas 的下一行

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:24 24 4
gpt4 key购买 nike

我在 Pandas 中有以下数据框

   code   date       tank    product    time_frst   time_lst   qty_frst   qty_lst
123 2019-01-01 1 MS 02:00:00 10:00:00 234 100
123 2019-01-01 2 HS 02:30:00 19:00:00 200 50
123 2019-01-01 3 MS 00:30:00 22:00:00 300 500

我想要的数据框如下

  code    date        tank    product      time        qty
123 2019-01-01 1 MS 02:00:00 234
123 2019-01-01 1 MS 10:00:00 100
123 2019-01-01 2 HS 02:30:00 200
123 2019-01-01 2 HS 19:00:00 50
123 2019-01-01 3 MS 00:30:00 300
123 2019-01-01 3 MS 22:00:00 500

我怎样才能在 pandas 中做到这一点?

最佳答案

在没有_的情况下通过所有列创建MultiIndex,因此可能将所有其他列拆分MultiIndex in columns和最后 reshape DataFrame.stack ,要删除不必要的列,首先使用 reset_index,然后将 MultiIndex in index 转换为列:

df = df.set_index(['code','date','tank','product'])
df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index(level=4, drop=True).reset_index()
print (df)
code date tank product qty time
0 123 2019-01-01 1 MS 234 02:00:00
1 123 2019-01-01 1 MS 100 10:00:00
2 123 2019-01-01 2 HS 200 02:30:00
3 123 2019-01-01 2 HS 50 19:00:00
4 123 2019-01-01 3 MS 300 00:30:00
5 123 2019-01-01 3 MS 500 22:00:00

关于python - 如何将列移到 Pandas 的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57428100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com