I have two pandas DataFrames df1 and df2 and I want to transform them in order that they keep values only for the index that are common to the 2 dataframes.
df1
You can pd.merge them with an intermediary DataFrame created with the indexes of the other DataFrame:
df2_indexes = pd.DataFrame(index=df2.index)
df1 = pd.merge(df1, df2_indexes, left_index=True, right_index=True)
df1_indexes = pd.DataFrame(index=df1.index)
df2 = pd.merge(df2, df1_indexes, left_index=True, right_index=True)
or you can use pd.eval:
df2_indexes = df2.index.values
df1 = df1[eval("df1.index in df2_indexes"]
df1_indexes = df1.index.values
df2 = df2[eval("df2.index in df1_indexes"]
The index object has some set-like properties so you simply can take the intersection as follows:
df1 = df1.reindex[ df1.index & df2.index ]
This retains the order of the first dataframe in the intersection, df
.