简体   繁体   中英

Finding common elements in panda dataframes

I have made a dataFrame like this

data = [['Football', 'x'], ['Football', 'y'], ['Football', 'z'], ['Volleyball', 'a' ], ['Volleyball', 'x'], ['Volleyball', 'y'], ['ruggby', 'd'], ['ruggby', 'e'], ['ruggby', 'f'] ] 

df = pd.DataFrame(data, columns = ['Name', 'Country'])

And I have made different dataframes as follows

sports = [v for k, v in df.groupby('Name')]

Then I'm checking the common country from the following codes

numbers=[]
for x in range(len(sports)):
    for y in range(len(sports)):
        try:
            common_sports=sports[x]['Country'].isin(sports[y]['Country']).value_counts()
            numbers.append(common_sports[True])
        except:
            numbers.append(float('inf'))

print(numbers)

Is there a good faster pandas way to write the last bunch of codes without a for loop? So that i willl get the same result.

results will be

[3, 2, inf, 2, 3, inf, inf, inf, 3]

If I understand you correctly, you want to do sum of common values between the column 'Name' and 'Country':

import numpy as np
import pandas as pd

data = [['Football', 'x'], ['Football', 'y'], ['Football', 'z'], ['Volleyball', 'a' ], ['Volleyball', 'x'], ['Volleyball', 'y'], ['ruggby', 'd'], ['ruggby', 'e'], ['ruggby', 'f'] ]
df = pd.DataFrame(data, columns = ['Name', 'Country'])

df = df.assign(foo=1).merge(df.assign(foo=1), on='foo')
df = df.groupby(['Name_x', 'Name_y'])['Country_x', 'Country_y'].apply(lambda x: len( set(x.Country_x) & set(x.Country_y) )).reset_index()
print(df[0].replace(0, np.inf).values.tolist())

Prints:

[3.0, 2.0, inf, 2.0, 3.0, inf, inf, inf, 3.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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