Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

Is it possible to only merge some columns? I have a DataFrame df1 with columns x, y, z, and df2 with columns x, a ,b, c, d, e, f, etc.

I want to merge the two DataFrames on x, but I only want to merge columns df2.a, df2.b - not the entire DataFrame.

The result would be a DataFrame with x, y, z, a, b.

I could merge then delete the unwanted columns, but it seems like there is a better method.

1 Answer

0 votes
by (41.4k points)

A simple solution to this is to merge the sub-DataFrame :

df2[list('xab')]  # df2 but only with columns x, a, and b

df1.merge(df2[list('xab')])

If you want to learn more about Pandas then visit this Python Course designed by the industrial experts.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...