【问题标题】:Python pandas: how to assign value to new column if key is in other columnPython pandas:如果键在其他列中,如何为新列赋值
【发布时间】:2018-05-09 01:50:34
【问题描述】:

我有一个数据框,想检查一列中字符串的任何部分是否是给定字典中的键,如果是,则将此键的值分配给新列。

dict = {'Apple': 'Fruit', 'Chicken': 'Meat'}

expected df:

#     String           New Column
# 1   'Red apple'      'Fruit'
# 2   'Fried chicken'  'Meat'

我发现这篇文章与我需要做的非常接近,但我找不到使用字典的解决方案:python pandas if column string contains word flag

我希望这是有道理的,感谢您的帮助!

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    我们需要将您的dict 和您的df 中所有键的字符都更改为大写,然后我们只需apply 带有检查功能

    d={x.upper(): y for x,y in d.items()}
    
    df['New']=df.String.str.upper().apply(lambda x : ''.join([v if k in x  else '' for k,v in d.items()]))
    
    df
              String    New
    0      Red apple  Fruit
    1  Fried chicken   Meat
    

    【讨论】:

    • 一个很好的解决方案 +1。使用大写字母的任何具体原因?
    • @HarvIpan dict 的键是 Apple,但在 df 中是 apple :-)
    • @Wen:太棒了!太感谢了! :-)
    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多