我已经制作了一个这样的dataFrame
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'])
我做了如下不同的数据框
sports = [v for k, v in df.groupby('Name')]
然后我要从以下代码中检查共同国家/地区
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)
在没有for循环的情况下,有没有一种更快的熊猫方法来编写最后一堆代码?这样我就可以得到相同的结果。
结果将
[3, 2, inf, 2, 3, inf, inf, inf, 3]
答案 0 :(得分:1)
如果我对您的理解正确,那么您想要对“名称”和“国家/地区”列之间的通用值求和:
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())
打印:
[3.0, 2.0, inf, 2.0, 3.0, inf, inf, inf, 3.0]