我有如下所示格式的数据框:
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
现在我想合并列 R_1、R_2 和 R_3,并将它们分配到标题 Store_R 下,同时在标题 Store_S 下类似地组合列 S_1、S_2 和 S_3,这样输出现在的格式如下所示:
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
请您参考如下方法:
您可以 concat
按 filter
过滤 Dataframes
:
#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
创建 MultiIndex.from_tuples
的另一种解决方案但必要的是,第一列都是 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
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