簡體   English   中英

遍歷兩個熊貓數據幀並從df1中找到一個字符串,其中a在df2中

[英]iterating through two pandas data frames and finding a string from df1 that a is in df2

我有兩個Dataframe,我們稱它們為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 str.findall df2中的Term,那么我們需要gourpby將df2中的公共Term sum 。到目前為止,我們只需要使用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

更新如果是這樣的話,你可能希望看到unnestingstr.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM