首页 > 解决方案 > Pandas:检查另一列中是否存在子字符串,然后创建一个具有特定值的新列

问题描述

我有这个数据框:

Receipt Description Card Member Account Cost
200a apple adam 08203928 $2
20022a pear bob 08203228 $7
202a orange alice 0820321228 $8

我想检查description列中的值是否包含特定的子字符串。例如,第一行 (adam) 的描述为“apple”。我想检查该description列中是否存在子字符串“appl”。

如果是这样,我想创建一个名为的新列Data,然后存储 value need more apples。如果没有找到“appl”的子字符串,我不想在此列中存储任何内容。

这就是预期的新数据框的样子。

Receipt Description Card Member Account Cost **Data**
200a apple adam 08203928 $2 need more apples
20022a pear bob 08203228 $7
202a orange alice 0820321228 $8

标签: pythonpandas

解决方案


你可以试试这个:

示例 1:

df["**Data**"] = df["Description"].map(lambda x: "apple containes" if "appl" in x else '')

示例 2

如果您有要检查的每个水果的映射,那么您可以像这样创建

desc = {"appl":"need more apples","pear": "need more pear"}

def check_desc(x):
    for key in desc:
        if key.lower() in x.lower():
            return desc[key]
    return ''

df["**Data**"] = df["Description"].map(lambda x: check_desc(x))

推荐阅读