我有两个熊猫数据帧df1和df2,我想对它们进行转换,以便它们只保留两个数据帧共有的索引值
df1
值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
值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
值1
28/11/2000 -0.055276
29/11/2000 0.027427
30/11/2000 0.066009
df2
值2
28/11/2000 -0.026316
29/11/2000 0.015222
30/11/2000 -0.024480
您可以使用Index.intersection+DataFrame.loc:
idx=df1.index.intersection(df2.index)
打印(idx)
索引(['28/11/2000'、'29/11/2000'、'30/11/2000'],dtype='object')
具有numpy.intersect1d的替代解决方案:
idx=np.intersect1d(df1.index,df2.index)
打印(idx)
['28/11/2000' '29/11/2000' '30/11/2000']
df1=df1.loc[idx]
打印(df1)
价值观1
28/11/2000 -0.055276
29/11/2000 0.027427
30/11/2000 0.066009
df2=df2.loc[idx]