遍历两个pandas数据帧并从df1中找到一个字符串,该字符串位于df2中

2024-04-28 11:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,我们称它们为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)


Tags: term1thatisthisfull术语ohdf1
1条回答
网友
1楼 · 发布于 2024-04-28 11:45:23

IIUC使用str.findall从df1中提取df2中的项,然后我们需要gourpbysumdf2中的公共项。到目前为止,我们只需要使用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之后看到unnesting,请更新

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

相关问题 更多 >