![](/img/trans.png)
[英]If partial string in the same pandas column match then update the value in another column
[英]Conditional Update of Column based on partial string match in another column
可重現的數據幀
表格1
table1 = {'Text':['hello this is', 'a test data', 'frame for', 'stackoverflow'], 'keyid':[20, 21, 19, 18]}
table1 = pd.DataFrame(table1)
Text keyid
0 hello this is 20
1 a test data 21
2 frame for 19
3 stackoverflow 18
表 2
table2 = {'word': ['hello', 'over','for','is', 'hey'], 'count': [1, 2, 1, 3, 5]}
table2 = pd.DataFrame(table2)
word count
0 hello 1
1 over 2
2 for 1
3 is 3
4 hey 5
我正在嘗試根據條件創建表 1 的條件更新:如果在表 1 的“文本”列中找到表 2“字”列中的字符串,則從表 2 中調出“計數”列,否則將其保留為 NA。
預期產出
Text keyid count
0 hello this is 20 1
1 a test data 21 NA
2 frame for 19 1
3 stackoverflow 18 NA
注意:'over' 出現在 Text 列中,但它沒有反映在預期的輸出中,因為我不需要在字符串本身內進行匹配。
有人能指出我正確的方向嗎?
您可以將series.str.extract()
與按字邊界的模式一起使用,然后map
以獲取相應的 table2 count
:
d=table2.set_index('word')['count']
p='({})'.format('\\b|\\b'.join(table2.word))
#'(hello\\b|\\bover\\b|\\bfor\\b|\\bis\\b|\\bhey)'
table1['count']=table1.Text.str.extract(p,expand=False).map(d)
print(table1)
Text keyid count
0 hello this is 20 1.0
1 a test data 21 NaN
2 frame for 19 1.0
3 stackoverflow 18 NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.