如何获得两个 pandas 数据框的公共索​​引? [英] How to get the common index of two pandas dataframes?

查看:48
本文介绍了如何获得两个 pandas 数据框的公共索​​引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个pda数据框df1和df2,我想对其进行转换,以便它们仅保留两个数据框共有的索引值。

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

                      values 1
0                            
28/11/2000          -0.055276
29/11/2000           0.027427
30/11/2000           0.066009
01/12/2000           0.012749
04/12/2000           0.113892

df2

                       values 2

24/11/2000            -0.004808
27/11/2000            -0.001812
28/11/2000            -0.026316
29/11/2000             0.015222
30/11/2000            -0.024480

成为

df1

                     value 1

28/11/2000          -0.055276
29/11/2000           0.027427
30/11/2000           0.066009

df2

                       value 2

28/11/2000            -0.026316
29/11/2000             0.015222
30/11/2000            -0.024480


推荐答案

您可以使用 Index.intersection + DataFrame.loc

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')

带有 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]

这篇关于如何获得两个 pandas 数据框的公共索​​引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆