遍历两个 Pandas 数据帧,并从 DF1 中查找 A 在 DF2 中的字符串



我有两个数据帧,我们称它们为 df1 和 df2。

DF1

Term Served term1 82321 term2 54232 term3 34323 term4 1231

DF2

Full Term clicks this is term1 233 oh boy this is term2 122 yea that's right term1 1121 oh no not that term4 313123

我想逐行浏览,每次发现 df1 中的术语出现在 df2 中。之后,我想总结该特定术语的所有点击次数。输出看起来像,

Term Served Clicks term1 82321 1354 term2 54232 122 term3 34323 0 term4 1231 313123

这是我到目前为止所拥有的。我还没有抓住 df1 中的术语出现在 df2 中的所有时间。下面的代码只循环遍历 df1 中的第一行。也许我不明白str.findall()或者我的循环错误。

for index, row in df1.iterrows(): for row2 in df2.iteritems(): full_headline = df2['Full Term'].str.findall(row[0]) print(full_headline)

IIUC 使用str.findall从 df1 扩展 df2 中的项,那么我们需要在 df2 中gourpbysum通用项。到目前为止,我们只需要使用map将结果分配回 df1

df2['Full Term']=df2['Full Term'].str.findall('|'.join(df1.Term)).str[0]
s=df2.groupby('Full Term').clicks.sum()
df1['Clicks']=df1.Term.map(s).fillna(0)
df1
Out[114]: 
Term  Served    Clicks
0  term1   82321    1354.0
1  term2   54232     122.0
2  term3   34323       0.0
3  term4    1231  313123.0

如果是这种情况,请更新,您可能希望在str.findall后看到取消嵌套

df2['Full Term']=df2['Full Term'].str.findall('|'.join(df1.Term))
df2=df2[df2['Full Term'].astype(bool)].copy()#adding here
def unnesting(df, explode):
idx=df.index.repeat(df[explode[0]].str.len())
df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
df1.index=idx
return df1.join(df.drop(explode,1),how='left')
s=unnesting(df2,['Full Term']).groupby('Full Term').clicks.sum()
df1['Clicks'] = df1.Term.map(s).fillna(0)
df1
Out[137]: 
Term  Served  Clicks
0  term1   82321    1354
1  term2   54232     355
2  term3   34323     233
3  term4    1231  313123

相关内容

最新更新