【发布时间】:2021-01-17 14:15:18
【问题描述】:
警告:你即将看到一个非常。非常糟糕的一段代码。我知道,我只是不知道如何解决它。我尝试了几种替代方案,但我缺乏 Pandas 的经验(或 numpy - 也许这是一个更好的选择)。您已被警告!
我有两个数据框,我需要从数据框 2 上存在的数据框 1 中查找匹配信息。让我告诉你:
# DataFrame 1
d1 = {'name': ['John Doe', 'Jane Doe'],
'email': ['john@example.com', 'jane@example.com'],
'phone': ['15181111111', '15182222222']}
df1 = pd.DataFrame(data=d1)
###
# DataFrame 2
d2 = {'name': ['Fred Flinstone', 'Barney Rubble', 'Betty Rubble'],
'email': ['john@example.com', 'barney@example.com', 'betty@example.com'],
'Mobile': ['15183333333', '15182222222', '15184444444'],
'LandLine': ['15181111111', '15182222222', '15185555555']}
df2 = pd.DataFrame(data=d2)
所以我的目标是找出df2 中的哪些行与df1(电子邮件、电话)中可用数据的每一部分(但名称)相匹配。找到匹配项后,我需要记录两个数据帧中的所有数据。
现在,开始咬指甲,深呼吸,看看我正在做的耻辱。它确实有效,但您很快就会意识到问题所在:
# Empty dataframe to store matches
df_found = pd.DataFrame(columns=['df1 Name', 'df1 email', 'df1 phone', 'df2 name', 'df2 email', 'df2 mobile', 'df2 landline'])
# Search for matches
for row_df1 in df1.itertuples():
tmp_df = df2[df2['email'].str.contains(row_df1.email, na=False, case=False)]
if(len(tmp_df) > 0):
for row_df2 in tmp_df.itertuples():
df_found.loc[len(df_found)] = [row_df1.name, row_df1.email, row_df1.phone, row_df2.name, row_df2.email, row_df2.Mobile, row_df2.LandLine]
tmp_df = df2[df2['Mobile'].str.contains(row_df1.phone, na=False, case=False)]
if(len(tmp_df) > 0):
for row_df2 in tmp_df.itertuples():
df_found.loc[len(df_found)] = [row_df1.name, row_df1.email, row_df1.phone, row_df2.name, row_df2.email, row_df2.Mobile, row_df2.LandLine]
tmp_df = df2[df2['LandLine'].str.contains(row_df1.phone, na=False, case=False)]
if(len(tmp_df) > 0):
for row_df2 in tmp_df.itertuples():
df_found.loc[len(df_found)] = [row_df1.name, row_df1.email, row_df1.phone, row_df2.name, row_df2.email, row_df2.Mobile, row_df2.LandLine]
#Drop duplicates - Yes of course there are many
df_found.drop_duplicates(keep='first',inplace=True)
你去吧,我在一个循环中有一系列循环,每个循环都遍历相同的数据并增加一个 临时 数据帧和一个 match holder 数据帧。
最后我得到了我的结果:
但是速度太可怕了。我的真实数据框第一列有 29 列,第二列有 55 列。第一个大约有 10 万条记录,第二个大约有 50 万条记录。现在,在没有 GPU 和 16GB RAM 的 i7 中,这个过程大约需要四个小时。
如果您已经能够呼吸并且不再用头撞墙,我将不胜感激有关如何正确执行此操作的一些想法。
非常感谢!
【问题讨论】:
标签: python pandas dataframe search match