【问题标题】:Pandas: Check if a substring exists in another column then create a new column with a specific valuePandas:检查另一列中是否存在子字符串,然后创建一个具有特定值的新列
【发布时间】:2021-11-26 03:10:50
【问题描述】:

我有这个数据框:

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

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

如果是这样,那么我想创建一个名为 Data 的新列,然后它将存储值 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

【问题讨论】:

标签: python pandas


【解决方案1】:

你可以试试这个:

示例 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))

【讨论】:

  • 感谢您的解释和更多映射!
  • @Jacques 如果我的解决方案对您有用,请点赞。谢谢
【解决方案2】:

包含一个字符串和 np.where() 来检查它是否包含一个字符串。我愿意。

df['**Data**'] = np.where(df['Description'].str.contains('apple'),'need more apples','')

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 2022-07-06
    • 2022-11-10
    • 2022-07-01
    • 2021-10-26
    • 2019-02-28
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多