【发布时间】:2018-10-18 08:35:33
【问题描述】:
给定一个 DataFrame,在 DataFrame 中查找与给定值列表部分匹配的行的最佳方法是什么。
目前,我在 DataFrame (df1) 中有一行给定值,我遍历这些值,然后将一个函数应用于另一个 DataFrame (df2) 的每一行,该函数计算行中有多少值符合条件,然后返回一个计数高于某个值的第二个 DataFrame 的子集。
def partialMatch(row, conditions):
count = 0
if(row['ResidenceZip'] == conditions['ResidenceZip']):
count+=1
if(row['FirstName'] == conditions['FirstName']):
count +=1
if(row['LastName'] == conditions['LastName']):
count +=1
if(row['Birthday'] == conditions['Birthday']):
count+=1
return count
concat_all = []
for i, row in df1.iterrows():
c = {'ResidenceZip': row['ResidenceZip'], 'FirstName':row['FirstName'],
'LastName': row['LastName'],'Birthday': row['Birthday']}
df2['count'] = df2.apply(lambda x: partialMatch(x, c), axis = 1)
x1 = df2[df2['count']>=3]
concat_all.append(x1)
这可行,但速度很慢。有关加快此过程的任何提示?
例如,在下面的两个数据帧上运行代码,df1 的第一行将返回 df2 的前三行,而不是最后两行。
df1
FirstName|LastName | Birthday | ResidenceZip
John | Doe | 1/1/2000 | 99999
Rob | A | 1/1/2010 | 19499
df2
FirstName|LastName | Birthday | ResidenceZip | count
John | Doe | 1/1/2000 | 99999 | 3
John | Doe | 1/1/2000 | 99999 | 3
John | Doex | 1/1/2000 | 99999 | 3
Joha | Doex | 1/1/2000 | 99999 | 2
Joha | Doex | 9/9/2000 | 99999 | 1
Rob | A | 9/9/2009 | 19499 | 0
【问题讨论】:
-
如果可能,请提供示例输入数据框和您的预期输出?