How to get the common index of two pandas dataframes?

前端 未结 8 1387
野趣味
野趣味 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"]
    
    0 讨论(0)
  • 2021-02-19 04:04

    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.

    0 讨论(0)
提交回复
热议问题