简体   繁体   English

检查 pandas 系列中的每一行是否包含使用 apply 的列表中的字符串?

[英]Check if each row in a pandas series contains a string from a list using apply?

I'm trying to add a column to the DF, depending on whether other column's value contains any of the strings in a list.我正在尝试向 DF 添加一列,具体取决于其他列的值是否包含列表中的任何字符串。

The list is:名单是:

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

And so far I've tried:到目前为止,我已经尝试过:

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

And this:和这个:

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

Among some other variations... I've seen other questions but they're mostly related to the opposite problem (checking whether a column's value is contained by a string in a list)在其他一些变化中......我见过其他问题,但它们大多与相反的问题有关(检查列的值是否包含在列表中的字符串中)

I could use your help!我可以使用你的帮助! Thanks!!谢谢!!

You can use np.where and str.contains :您可以使用np.wherestr.contains

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

Output: Output:

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

i think you can use isin我认为你可以使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于 Pandas dataframe 中的每一行,检查行是否包含列表中的字符串 - For each row in Pandas dataframe, check if row contains string from list Python Pandas:检查系列是否包含列表中的字符串 - Python Pandas: check if Series contains a string from list 使用系列中的字符串检查熊猫中的 str.contains - check str.contains in pandas using string from series 在 Pandas 列中搜索每行值包含列表的字符串 - Searching Pandas Column for string where each row value contains list 从 pandas 系列中的每一行中提取某个字符串的最后一次出现 - Extracting last occurrence of a certain string from each row in a pandas series Pandas-如何检查DF行中的字符串列表是否包含另一个DF中的任何串联字符串? - Pandas- How to check if list of strings in DF row contains any of strings in series in another DF? 检查 pandas.core.series.Series 是否包含 Python 中的特定字符串 - Check if a pandas.core.series.Series contains a specific string in Python 检查 pandas dataframe 是否包含项目列表中的特定字符串 - Check if pandas dataframe contains specific string from a list of items 检查 Series 是否包含列表中的任何元素 - Check if Series contains any element from a list 如果pandas系列中的字符串包含另一个pandas数据帧中的字符串 - if string in pandas series contains a string from another pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM