FMM
FMM

Reputation: 27

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

Suppose I have

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

How do I delete the rows from df1 that don't match the index of those in df2? I want to be able to keep the original values in the remaining rows of df1.

Upvotes: 1

Views: 58

Answers (2)

FMM
FMM

Reputation: 27

I found that this works as well:

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

Upvotes: 0

ashkangh
ashkangh

Reputation: 1624

Try this:

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

Upvotes: 2

Related Questions