Var*_*ava 2 python header multiple-columns dataframe pandas
我的数据框格式如下所示:
Product R_1 R_2 R_3 S_1 S_2 S_3
x 2 4 21 12 43 54
y 5 2 12 42 31 12
Run Code Online (Sandbox Code Playgroud)
现在我想将列 R_1、R_2 和 R_3 组合在一起,并将它们分配到标题 Store_R 下,同时类似地将列 S_1、S_2 和 S_3 组合到标题 Store_S 下,这样输出现在的格式如下所示:
Store_R Store_S
Product R_1 R_2 R_3 S_1 S_2 S_3
x 2 4 21 12 43 54
y 5 2 12 42 31 12
Run Code Online (Sandbox Code Playgroud)
您可以按以下条件concat
过滤:Dataframes
filter
#if Product is column set to index
df = df.set_index('Product')
print (pd.concat([df.filter(like='R'),
df.filter(like='S')],
axis=1,
keys=('Store_R','Store_S')))
Store_R Store_S
R_1 R_2 R_3 S_1 S_2 S_3
Product
x 2 4 21 12 43 54
y 5 2 12 42 31 12
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是创建MultiIndex.from_tuples
但必需的,第一列是 all R
,然后是S
。因为值是已分配的,并且某些值可能会错误对齐。
colsR = [('Store_R', col) for col in df.columns if 'R' in col]
colsS = [('Store_S', col) for col in df.columns if 'S' in col]
df = df.set_index('Product')
df.columns = pd.MultiIndex.from_tuples(colsR + colsS)
print (df)
Store_R Store_S
R_1 R_2 R_3 S_1 S_2 S_3
Product
x 2 4 21 12 43 54
y 5 2 12 42 31 12
Run Code Online (Sandbox Code Playgroud)
sort_index
可以帮助对列名进行排序:
print (df)
Product S_1 R_2 R_3 S_12 S_2 S_3
0 x 2 4 21 12 43 54
1 y 5 2 12 42 31 12
colsR = [('Store_R', col) for col in df.columns if 'R' in col]
colsS = [('Store_S', col) for col in df.columns if 'S' in col]
df = df.set_index('Product').sort_index(axis=1)
df.columns = pd.MultiIndex.from_tuples(colsR + colsS)
print (df)
Store_R Store_S
R_2 R_3 S_1 S_12 S_2 S_3
Product
x 4 21 2 12 43 54
y 2 12 5 42 31 12
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3904 次 |
最近记录: |