Polly
Polly

Reputation: 1097

How to intersect two files in Python using pandas?

I have two dataframes, A and B, that have some common column names. Like that:

A                            B
Date Birth             Date Place City
156    0               642    M     K
521    1               765    O     L
765    1               111    S     K
832    0               521    M     S

I need to get a new dataframe which will consist of the intersection of A and B basd on their common column + data from 2nd dataframe:

Date  Place  City
765    O      L
521    M      S

Is there any faster way than iterate through the items, as i'm trying to do?'

f=''
for i in A['Date'].iteritems():
    for j in B['Date'].iteritems():
        if i==j:
           f.to_csv([j]+B['Place']+['City']) 

Upvotes: 0

Views: 614

Answers (1)

jezrael
jezrael

Reputation: 862611

You can use merge with drop:

print pd.merge(A,B, on=['Date']).drop('Birth', axis=1)
   Date Place City
0   521     M    S
1   765     O    L

Next solution create subset with column Date and then merge it with DataFrame B:

print pd.merge(A[['Date']],B, on=['Date'])
   Date Place City
0   521     M    S
1   765     O    L

Upvotes: 2

Related Questions