如何在pandas中将列移至下一行

2024-04-26 01:05:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫中有以下数据帧

   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

我怎样才能在熊猫身上做呢


Tags: 数据datetimecodeproductmshsqty
1条回答
网友
1楼 · 发布于 2024-04-26 01:05:39

通过所有不带_的列创建MultiIndex,因此可能将split所有其他列创建为MultiIndex in columns,最后通过^{}重新形状,对于删除不必要的列,使用第一个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

相关问题 更多 >