1
votes

I have to two pandas dataframe. Say,

df1

    |A|B|C
2001|1|2|3
2002|2|3|9
2003|2|1|3

df2

    |A|C|D
2001|3|2|2
2002|1|9|9
2003|4|3|1

so column names A and C exist for both two dataframe, i would like to filter them for each of the two dataframes. In other words, I need two new data frames.

new df1 (column B is deleted from original df1 as 'B' is not a column name in df2)

    |A|C
2001|1|3
2002|2|9
2003|2|3

new df2(column D is deleted from original df2 as 'D' is not a column name in df1)

    |A|C
2001|3|2
2002|1|9
2003|4|3

I know i can merge two data frames and then split them again to achieve my results. Are there better ways to complete this?

1

1 Answers

2
votes

Get common columns

In [213]: cols = df1.columns.intersection(df2.columns)

In [214]: df1[cols]
Out[214]:
      A  C
-
2001  1  3
2002  2  9
2003  2  3

In [215]: df2[cols]
Out[215]:
      A  C
-
2001  3  2
2002  1  9
2003  4  3