2017-02-07 40 views
3

如何在pandas數據透視操作後重命名具有多個級別的列?熊貓數據透視表重命名欄

下面是一些代碼,以生成測試數據:

import pandas as pd 
df = pd.DataFrame({ 
    'c0': ['A','A','B','C'], 
    'c01': ['A','A1','B','C'], 
    'c02': ['b','b','d','c'], 
    'v1': [1, 3,4,5], 
    'v2': [1, 3,4,5]}) 

print(df) 

給出了一個測試數據幀:

c0 c01 c02 v1 v2 
0 A A b 1 1 
1 A A1 b 3 3 
2 B B d 4 4 
3 C C c 5 5 

施加樞軸

df2 = pd.pivot_table(df, index=["c0"], columns=["c01","c02"], values=["v1","v2"]) 
df2 = df2.reset_index() 

給出

output1

如何通過連接級別重命名列? 與格式 <c01 value>_<c02 value>_<v1>

例如第一列看起來應該像 "A_b_v1"

加盟級別的順序是不是對我來說真的很重要。

回答

6

你可以通過其中的每個元素是一個元組,把它解析,並加入他們回到你想要的順序列循環:

df2 = pd.pivot_table(df, index=["c0"], columns=["c01","c02"], values=["v1","v2"]) 

# Use the list comprehension to make a list of new column names and assign it back 
# to the DataFrame columns attribute. 
df2.columns = ["_".join((j,k,i)) for i,j,k in df2.columns] 
df2.reset_index() 

enter image description here

+2

謝謝'''[「_」。加入(str(s).strip()for s in col if s)for col in df2.columns]'''作爲一個通用的解決方案,與層數無關 – muon