【问题标题】:Check if each row in a pandas series contains a string from a list using apply?使用apply检查熊猫系列中的每一行是否包含列表中的字符串?
【发布时间】:2020-09-19 06:52:33
【问题描述】:

我正在尝试向 DF 添加一列,具体取决于其他列的值是否包含列表中的任何字符串。

名单是:

services = [
        "TELECOM",
        "AYSA",
        "PERSONAL"
]

到目前为止,我已经尝试过:

payments["category"] = "services" if payments["concept"].contains(service for service in services) else ""

还有这个:

payments["category"] = payments["concept"].apply(lambda x: "services" if x.contains(service) for service in services) else ""

在其他一些变体中...我见过其他问题,但它们大多与相反的问题有关(检查列的值是否包含在列表中的字符串中)

我可以使用你的帮助!谢谢!!

【问题讨论】:

    标签: python pandas list dataframe list-comprehension


    【解决方案1】:

    我认为你可以使用 isin

    payments['category'] = np.where(
        payments['concept'].isin(services),
        'services', '')
    
    import pandas
    import numpy
    
    dic = {"concept": ["TELECOM", "NULL"]}
    
    payments = pandas.DataFrame.from_dict(dic)
    
    payments["category"] = numpy.where(payments["concept"].isin(["TELECOM", "AYSA", "PERSONAL"]), "services", "")
    
    print(payments)
    

    【讨论】:

    • 这对我不起作用,但感谢您的快速回答!
    • @D. Seah,isin func 不允许在 StringMethods 上使用
    【解决方案2】:

    您可以使用np.wherestr.contains

    payments['category'] = np.where(payments['concept'].str.contains('|'.join(services)),
                                    'services', '')
    

    输出:

            concept  category
    0       TELECOM  services
    1          AYSA  services
    2      PERSONAL  services
    3  other things          
    

    【讨论】:

    • 谢谢,效果很好!但是可以跳过已经定义了其他类别的行吗?我正在尝试像payments['category'] = np.where((payments['concept'].str.contains('|'.join(online_shopping))) & (payments["category"] == ''), 'online_shopping', '') 这样运行第二行,但第二个条件不起作用...
    • 在这种情况下,您应该使用允许多个条件的 np.select。
    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2017-06-27
    • 2014-11-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多