[英]Adding a header name to a group of columns in a dataframe in 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
現在我想對列 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
您可以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
創建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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.