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

Merge from width to length

WBOY
Release: 2024-02-09 23:50:04
forward
713 people have browsed it

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]})
Copy after login

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)
Copy after login

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)
)
Copy after login

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template