【发布时间】:2020-10-25 03:49:46
【问题描述】:
如何在 column1 上应用条件,其中字符串 仅包含 给定一组关键字,而不是 包含 给定一组关键字。 强调“仅”这个词
import pandas as pd
import numpy as np
import re
d = {'_id': [1, 2, 3, 4, 5, 6, 7],
'column1': ['FullName', 'custfullnm', 'nm123', 'sitenm', 'full12', 'suplnm', 'countryfulln'],
'column2': ['', '', '', '', '', '', '']}
df = pd.DataFrame(data=d)
key_words = ["full", "nm", "name", "txt", "[0-9]"]
check = f"{'|'.join(key_words)}"
mand_key = "full"
df["column2"] = np.where(
df.column1.str.contains(mand_key, case=False)
& (df.column1.str.contains(check, case=False, regex=True)),
"Full Name",
"",
)
想要的输出:
_id,column1,column2
1,FullName,Full Name
2,custfullnm,
3,nm123,
4,sitenm,
5,full12,Full Name
6,suplnm,
7,countryfullnm,
只有 FullName, full12 符合条件,原因如下:
FullName is only made of words from given set of keywords 'full' & 'name'
full12 is only made of words from given set of keywords 'full' & a number '12'
而rest不符合条件,原因如下:
custfullnm contains 'cust' not in given list of keywords though contains 'nm' & 'full'
nm123 dones't contain madate keyword 'full' though contains a number & 'nm'
sitename contains 'site' not in given list of keywords though contains 'name'
suplnm contains 'supl' not in given list of keywords though contains 'nm'
countryfullnm contains 'country' not in given list of keywords though contains 'nm' & 'full'
【问题讨论】: