我有一个Pandas DataFrame
data = {
"SomeCol":[1,2],
"Group1":['x','y'],
"Group2":['a','b'],
"SomeAgg":[100,200]
}
df = pd.DataFrame(data)
SomeCol Group1 Group2 SomeAgg
0 1 x a 100
1 2 y b 200
我怎么能得到这个:
SomeCol Var1 Var2 Var1_value Var2_value SomeAgg
0 1 Group1 Group2 x a 100
1 2 Group1 Group2 y b 200
我尝试了
pd.melt
函数,该函数仅提供一个变量和一个值列。任何帮助,将不胜感激
最佳答案
也可以不使用pd.melt
来实现该解决方案:
data = {
"SomeCol":[1,2],
"Group1":['x','y'],
"Group2":['a','b'],
"SomeAgg":[100,200]
}
df = pd.DataFrame(data)
col_names = ['Group1', 'Group2']
df['Var1'], df['Var2'] = col_names[0], col_names[1]
df = df.rename(columns={col_names[0]: 'Var1_Value', col_names[1]: 'Var2_Value'})
print(df)
SomeCol Var1_Value Var2_Value SomeAgg Var1 Var2
0 1 x a 100 Group1 Group2
1 2 y b 200 Group1 Group2
关于python - Pandas 融化以获得多个变量和值列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54958300/