2

I have two Pandas dataframes ie:

+-------+-------------------+--+
| Name  |       Class       |  |
+-------+-------------------+--+
| Alice | Physics           |  |
| Bob   | "" (Empty string) |  |
+-------+-------------------+--+

Table 2:

+-------+-----------+
| Name  |   Class   |
+-------+-----------+
| Alice | Chemistry |
| Bob   | Math      |
+-------+-----------+

Is there a way to combine it easily on the column Class so the resulting table is like:

+-------+--------------------+
| Name  |       Class        |
+-------+--------------------+
| Alice | Physics, Chemistry |
| Bob   | Math               |
+-------+--------------------+

I also want to make sure there are no extra commas when adding columns. Thanks!

1
  • 1
    Just append the two, groupby name, then concatenate Commented Jul 20, 2021 at 20:05

2 Answers 2

2
df = pd.DataFrame({'Name':['Alice','Bob'],
                   'Class':['Physics',np.nan]})
df2 = pd.DataFrame({'Name':['Alice','Bob'],
                   'Class':['Chemistry','Math']})

df3 = df.append(df2).dropna(subset=['Class']).groupby('Name')['Class'].apply(list).reset_index()

# to remove list
df3['Class'] = df3['Class'].apply(lambda x: ', '.join(x))
Sign up to request clarification or add additional context in comments.

Comments

1

Try with concat and groupby:

>>> pd.concat([df1, df2]).groupby("Name").agg(lambda x: ", ".join(i for i in x.tolist() if len(i.strip())>0)).reset_index()
                    
Name                Class     
Alice  Physics, Chemistry
Bob                  Math

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.