pandas split/merge 列可以基于其名称中的模式吗?

Can pandas split/merge columns based on patterns in their name?

能否根据列名称中的模式pandas拆分and/or合并列?这是 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它:

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

编辑: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