如果列中的值同时包含这两个词,则创建一个新列并映射该值

2024-05-23 22:40:36 发布

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

我有一个列名为“Campaign”的数据框

如果此列中的值包含“常规”和“PHD”, 然后,创建“学位”栏,填写“博士”

如果是“一般”和“BS”, 并填写“BS”

如果是“一般”和“MS”, 并填写“MS”

其他np.nan

我的代码不正确,我知道,但它可能会让您了解我在尝试做什么:

Campaign_Degree = []

for x in data['Campaign']:
if x.str.contains('General' and 'PHD'):
    data['Campaign_Degree'] == 'PHD'
    
    if x.str.contains('General' and 'BS'):
    data['Campaign_Degree'] == 'BS'
    
        if x.str.contains('General' and 'MS'):
        data['Campaign_Degree'] == 'MS'
    
else:
    data['Campaign_Degree'] == np.nan

Tags: and数据dataifbsnpnan常规
1条回答
网友
1楼 · 发布于 2024-05-23 22:40:36

试着这样做:

df = pd.DataFrame({'col':["General & PHD",
                          "General & BS",
                          "General & MS",
                          "other",
                          "Brand_ABC_PHD",
                          "asGeneraldasPHDasda",
                          "BSasdasdGeneralppp"]})

df["new"] = df.col[df.col.str.contains("General")].str.extract("(PHD|BS|MS)")

输出

df
                   col  new
0        General & PHD  PHD
1         General & BS   BS
2         General & MS   MS
3                other  NaN
4        Brand_ABC_PHD  NaN
5  asGeneraldasPHDasda  PHD
6   BSasdasdGeneralppp   BS

相关问题 更多 >