![](/img/trans.png)
[英]create labels in a new data frame column based on partial string match of a different column
[英]Data Frame: row content partial text match in a list , create new column
在這里,我試圖匹配行內容中的字符串列表,如果有匹配,則將該字符串復制到新列中作為新的新變量,下面是相同的可重現代碼。
import pandas as pd
d2 = {'condn':pd.Series(['4.10 < petal_length <= 5.10','sepal_length > 6.30','1.30 < petal_width <= 1.80','3.00 < sepal_width <= 3.30']),
'score':pd.Series([2,2,5,3])}
d2 = pd.DataFrame(d2)
ref_list = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
d2
預期 Output(新列:var_name)
這是我嘗試過但沒有成功的代碼。
for i in range(0,d2.shape[0]):
txt = temp_data.iloc[i,0]
if txt.isin(ref_list) :
d2.ix[i,2] = txt
使用OR分隔符將列表組合成一個字符串,並使用re運行列表推導以獲取匹配的組
import re
d2['var_name'] = [re.search(fr"{'|'.join(ref_list)}", ent).group()
for ent in d2.condn]
condn score var_name
0 4.10 < petal_length <= 5.10 2 petal_length
1 sepal_length > 6.30 2 sepal_length
2 1.30 < petal_width <= 1.80 5 petal_width
3 3.00 < sepal_width <= 3.30 3 sepal_width
您也可以使用以下代碼實現此目的:
d2['var_name'] = d2.condn.str.extract(fr"({'|'.join(ref_list)})")
F-strings :它們提供了一種更簡單(IMO)的方式來在字符串中嵌入值。 python 有幾種方法可以將字符串與變量結合起來,包括格式方法。 F弦只是讓它更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.