英文:
How to merge columns into single column in dataframe pandas?
问题
import pandas as pd
# Original dataframe
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)
# Melt the dataframe to achieve the desired format
melted_df = pd.melt(df_1, id_vars=['Parent', 'Family Name'], var_name='Money', value_name='Amount')
# Sort the melted dataframe by 'Parent' and 'Family Name'
sorted_df = melted_df.sort_values(by=['Parent', 'Family Name'])
print(sorted_df)
Output:
Parent Family Name Money Amount
0 Jack Everdeen Money A 10000.0
3 Jack Everdeen Money B 20000.0
1 Rita Lawrence Money A 4000.0
4 Rita Lawrence Money B 2000.0
2 Amy Donnie Money A 5000.0
5 Amy Donnie Money B 9000.0
This code will give you the desired output by melting the original dataframe and sorting it accordingly.
英文:
Original dataframe
Parent Family Name Money A Money B
Jack Everdeen 10000 20000
Rita Lawrence 4000 2000
Amy Donnie 5000 9000
What I want.
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
I tried it with pivot function but it does not work. My code is as follows.
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)
答案1
得分: 1
pd.melt(df_1, id_vars=['Parent','Family Name'], var_name='MoneyCol', value_name='Money').sort_values('Parent',ascending=False)
英文:
Melt it
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论