Home >Backend Development >Python Tutorial >Merge from width to length

Merge from width to length

WBOY
WBOYforward
2024-02-09 23:50:04715browse

Merge from width to length

Question content

Hello, I am trying to merge two data sets via:

df1=pd.dataframe({'company name':['a','b','c'],
               'analyst 1 name':['tom','mike',np.nan],
               'analyst 2 name':[np.nan,'alice',np.nan],
               'analyst 3 name':['jane','steve','alex']})

df2=pd.dataframe({'company name':['a','b','c'],
               'score 1':[3,5,np.nan],
               'score 2':[np.nan,1,np.nan],
               'score 3':[6,np.nan,11]})

df_desire=pd.dataframe({'company name':['a','a','b','b','b','c'],
               'analyst':['tom','jane','mike','alice','steve','alex'],
               'score':[3,6,5,1,np.nan,11]})

Basically, df1 contains the analyst name and df2 contains the score assigned by the analyst. I'm trying to merge the two into df_desire. The method of reading the two tables is: for company a, it is covered by two people, namely tom and jane, who assign 3 and 6 respectively. Note that although steve covers company b, I intentionally specify the score as na for robustness purposes.

What I did was:

pd.concat([df1.melt(id_vars='company name',value_vars=['analyst 1 name','analyst 2 name','analyst 3 name']),\
           df2.melt(id_vars='company name',value_vars=['score 1','score 2','score 3'])],axis=1)

I'm looking for a more elegant solution.


Correct answer


Attempt:

x = (
    df1.set_index("company name")
    .stack(dropna=false)
    .reset_index(name="name")
    .drop(columns="company name")
)
y = df2.set_index("company name").stack(dropna=false).reset_index(name="score")

print(
    pd.concat([x, y], axis=1)[["company name", "name", "score"]]
    .dropna(subset=["name", "score"], how="all")
    .reset_index(drop=true)
)

Print:

  company name   name  score
0            A    Tom    3.0
1            A   Jane    6.0
2            B   Mike    5.0
3            B  Alice    1.0
4            B  Steve    NaN
5            C   Alex   11.0

The above is the detailed content of Merge from width to length. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete