如何在数据框Pandas中将列合并为单列?

uubf1zoe  于 2023-01-07  发布在  其他
关注(0)|答案(2)|浏览(151)

原始 Dataframe

Parent  Family Name  Money A  Money B

Jack    Everdeen     10000    20000
Rita    Lawrence     4000     2000
Amy     Donnie       5000     9000

我想要的。

Parent  Family Name  Money     Money

Jack    Everdeen     Money A   10000    
Jack    Everdeen     Money B   20000
Rita    Lawrence     Money A   4000     
Rita    Lawrence     Money B   2000
Amy     Donnie       Money A   5000     
Amy     Donnie       Money B   9000

我尝试了它与透视功能,但它不工作。我的代码如下。

data_1 = [['Jack','Everdeen',10000,20000],['Rita','Lawrence',4000,2000],['Amy','Donnie',5000,9000]]
df_1 = pd.DataFrame(data_1,columns=['Parent','Family Name','Money A','Money B'],dtype=float)
print(df_1)
loading_pivot_table = pd.pivot_table(df_1
                                     ,index = ['Parent','Family Name']
                                     ,columns = ['Parent','Family Name']
                             ,values = ['Money A','Money B']
                            ,fill_value = 0)
#convert pivot table to DataFrame
loading_pivot_table_convert = loading_pivot_table.reset_index()
print(loading_pivot_table_convert)
zaq34kh6

zaq34kh61#

Melt

pd.melt(df_1, id_vars=['Parent','Family Name'], var_name='MoneyCol', value_name='Money').sort_values('Parent',ascending=False)
Out[13]: 
  Parent Family Name MoneyCol    Money
1   Rita    Lawrence  Money A   4000.0
4   Rita    Lawrence  Money B   2000.0
0   Jack    Everdeen  Money A  10000.0
3   Jack    Everdeen  Money B  20000.0
2    Amy      Donnie  Money A   5000.0
5    Amy      Donnie  Money B   9000.0
0md85ypi

0md85ypi2#

你试过集合索引吗?

df.set_index(['a', 'b', 'c'])

相关问题