panda是否可以根据列名中的模式拆分和/或合并列?这是DataFrame
:
meas1_left meas1_right meas2_left meas2_right
0 1 2 3 4
1 6 7 8 9
我想把上面的数据和这个(我真的不在乎新帧是如何索引的(:
meas1 meas2 side
0 1 3 left
1 2 4 right
2 6 8 left
3 7 9 right
您可以首先通过split
:从列创建Multiindex
df.columns = df.columns.str.split('_', expand=True)
print (df)
meas1 meas2
left right left right
0 1 2 3 4
1 6 7 8 9
然后stack
it:
print (df.stack().reset_index(level=0, drop=True).reset_index())
index meas1 meas2
0 left 1 3
1 right 2 4
2 left 6 8
3 right 7 9
如果需要重命名列index
并更改列的顺序:
print (df.stack()
.reset_index(level=0, drop=True)
.reset_index()
.rename(columns={'index':'side'})[['meas1','meas2','side']])
meas1 meas2 side
0 1 3 left
1 2 4 right
2 6 8 left
3 7 9 right
EDIT:str
方法和index
从0.16.1开始实现,如果使用旧版本,请尝试:
a = df.columns.to_series().str.split('_').apply(pd.Series)
tuples = list(zip(a.iloc[:,0], a.iloc[:,1]))
print (tuples)
[('meas1', 'left'), ('meas1', 'right'), ('meas2', 'left'), ('meas2', 'right')]
df.columns = pd.MultiIndex.from_tuples(tuples)
print (df)
meas1 meas2
left right left right
0 1 2 3 4
1 6 7 8 9