How to get the common index of two pandas dataframes?

前端 未结 8 1429
野趣味
野趣味 2021-02-19 03:13

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

8条回答
  •  无人及你
    2021-02-19 04:03

    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"]
    

提交回复
热议问题