繁体   English   中英

如何从数据框中删除行并将其与另一个数据框进行比较并仅保留匹配的索引?

[英]How do I delete rows from a data frame comparing it to another data frame and only keeping matching indices?

假设我有

df1 = pd.DataFrame(rand(6,6), index = 'A B C D E F'.split(), columns = 'U V W X Y Z'.split())
df2 = pd.DataFrame(rand(3,6), index = 'B D E'.split(), columns = 'U V W X Y Z'.split())

如何从 df1 中删除与 df2 中的索引不匹配的行? 我希望能够将原始值保留在 df1 的剩余行中。

尝试这个:

df1.join(df2, rsuffix='_2', how='inner')[df1.columns]

Output:

    U   V   W   X   Y   Z
B   3   7   0   5   6   0
D   4   9   6   8   0   9
E   0   6   1   6   8   6

我发现这也有效:

df1[df1.index.isin(df2.index)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM