大熊猫将多组融合成单一柱

时间:2018-06-09 01:02:38

标签: python pandas dataframe transpose melt

原始DataFrame:

+----+----------+----------+----------+----------+
| ID |  var1hrs |  var2hrs |  ind1var |  ind2var |
+----+----------+----------+----------+----------+
|  1 |       55 |       45 |      123 |      456 |
|  2 |       48 |       60 |      331 |      222 |
+----+----------+----------+----------+----------+

目标数据框架:

+----+------------+------+------+
| ID |    type    |  hrs |  ind |
+----+------------+------+------+
|  1 |  primary   |   55 |  123 |
|  1 |  secondary |   45 |  456 |
|  2 |  primary   |   48 |  331 |
|  2 |  secondary |   60 |  222 |
+----+------------+------+------+

我如何将多组变量融合到一个标签列中?变量名中的“1”表示type =“primary”,“2”表示type =“secondary”。

2 个答案:

答案 0 :(得分:3)

修改列名后,我们可以使用wide_to_long

df.columns=df.columns.str[:4]
s=pd.wide_to_long(df,['var','ind'],i='ID',j='type').reset_index()
s=s.assign(type=s.type.map({'1':'primary','2':'secondary'})).sort_values('ID')
s

   ID       type  var  ind
0   1    primary   55  123
2   1  secondary   45  456
1   2    primary   48  331
3   2  secondary   60  222

答案 1 :(得分:3)

(内联评论)

# set ID as the index and sort columns
df = df.set_index('ID').sort_index(axis=1)

# extract primary columns
prim = df.filter(like='1')
prim.columns = ['ind', 'vars']
# extract secondary columns 
sec = df.filter(like='2')
sec.columns = ['ind', 'vars']

# concatenation + housekeeping
v = (pd.concat([prim, sec], keys=['primary', 'secondary'])
       .swaplevel(0, 1)
       .rename_axis(['ID', 'type'])
       .reset_index()
)

print(v)
   ID       type  ind  vars
0   1    primary  123    55
1   2    primary  331    48
2   1  secondary  456    45
3   2  secondary  222    60

这或多或少是一种有效的方法,即使步骤有点涉及。