I am new to Pandas and I have this below query, I have two dataframes df1 & df2 the df1 is an empty dataframe with 3 columns and df2 has 5 columns with some records.
Df1 Ex below | A| B| C| :--|:--:|--:| | | | |
Df2 Ex
A | B | D | C | E |
---|---|---|---|---|
1 | 2 | 3 | 4 | 5 |
1 | 2 | 3 | 4 | 5 |
1 | 2 | 3 | 4 | 5 |
If the column name matches, I want to copy all rows from df2 to df1. like below
DF1
A | B | C |
---|---|---|
1 | 2 | 4 |
1 | 2 | 4 |
1 | 2 | 4 |
it can be df1 or it can be a new data frame. Kindly help me with this query
CodePudding user response:
For general solution for filter of intersection of columns between both DataFrames use Index.intersection
:
Df1 = Df2.reindex(Df1.columns.intersection(Df2.columns, sort=False), axis=1)
If always exist all columns from Df1.columns
in Df2.columns
use:
Df1 = Df2[Df1.columns]
CodePudding user response:
No need to initialize an empty DataFrame, you can directly use:
df1 = df2[df1.columns].copy()