How to get the common index of two pandas dataframes?

前端 未结 8 1384
野趣味
野趣味 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 03:58

    You can use Index.intersection + DataFrame.loc:

    idx = df1.index.intersection(df2.index)
    print (idx)
    Index(['28/11/2000', '29/11/2000', '30/11/2000'], dtype='object')
    

    Alternative solution with numpy.intersect1d:

    idx = np.intersect1d(df1.index, df2.index)
    print (idx)
    ['28/11/2000' '29/11/2000' '30/11/2000']
    

    df1 = df1.loc[idx]
    print (df1)
                values 1
    28/11/2000 -0.055276
    29/11/2000  0.027427
    30/11/2000  0.066009
    
    df2 = df2.loc[idx]
    

提交回复
热议问题