1

I have following tables in a pandas dataframe:

ID1 ID2 Value1
Data1 Data2 Data11
ID1 ID2 Value2
Data1 Data2 Data12
ID1 ID2 Value3
Data1 Data2 Data13

My aim is a table of form:

ID1 ID2 Value1 Value2 Value3
Data1 Data2 Data11 Data12 Data13

What is the easiest way to do that with python?

2
  • Do you have three separate dataframes? Commented Dec 4, 2021 at 21:14
  • 1
    yes I have three seperate dataframes for each table. The aim-table should be in a new dataframe. Commented Dec 4, 2021 at 21:15

2 Answers 2

2
new_df = pd.concat([df1, df2, df3]).groupby(['ID1', 'ID2'], as_index=False).first()

Output:

>>> new_df
     ID1    ID2  Value1  Value2  Value3
0  Data1  Data2  Data11  Data12  Data13
Sign up to request clarification or add additional context in comments.

Comments

2

Perform multiple merges in a chain:

df1.merge(df2.merge(df3))

#      ID1    ID2  Value1  Value2  Value3
# 0  Data1  Data2  Data11  Data12  Data13

Or with functools.reduce syntax:

from functools import reduce
reduce(lambda L, R: L.merge(R, on=['ID1', 'ID2']), [df1, df2, df3])

1 Comment

lol. my answer: reduce(lambda dfL, dfR: dfL.merge(dfR, on=['ID1', 'ID2']), [df1, df2, df3])

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.