import pandas as pd
from datetime import datetime
df = pd.DataFrame({'origin': ['japan', 'japan','japan','japan'],
'pastime': ['baseball', 'sumo', 'keirin', 'football'],
datetime(2000,1,1) : [4,5,4,5],
datetime(2005,1,1) : [4, 3, 2, 1],
datetime(2010,1,1) : [4, 2, 2, 1]
})
我的数据框有很多带日期标签的列:
Index(['origin','pastime', 2000-01-01 00:00:00,
2005-01-01 00:00:00, 2010-01-01 00:00:00],
dtype='object')
我想将数据框重塑为具有列:
origin, pastime, date, value
第一个条目行将位于:
origin = japan
pastime = baseball
date = 2001-01-01
value = 4
我已经看到了使用
stack
将列作为索引推入行的示例,但就我而言,它也将'origin'和'pastime'列下推。我将如何进行转换?
最佳答案
我认为您正在寻找melt
:
df.melt(['origin', 'pastime'], var_name='date')
origin pastime date value
0 japan baseball 2005-01-01 4
1 japan sumo 2005-01-01 3
2 japan keirin 2005-01-01 2
3 japan football 2005-01-01 1
4 japan baseball 2010-01-01 4
5 japan sumo 2010-01-01 2
6 japan keirin 2010-01-01 2
7 japan football 2010-01-01 1
8 japan baseball 2000-01-01 4
9 japan sumo 2000-01-01 5
10 japan keirin 2000-01-01 4
11 japan football 2000-01-01 5