【问题标题】:Use Regex condition to create a new column in a Pandas DataFrame使用 Regex 条件在 Pandas DataFrame 中创建新列
【发布时间】:2017-08-10 21:48:00
【问题描述】:

这是我的问题。

我知道如何基于 RegEx 创建一个布尔列,如下所示:

df['New Column'] = df.columnA.str.match(regex)

在此示例中,“新列”将包含 True 或 False 值。

但是如果我想使用一个条件来表示“如果我的 RegEx 返回 true,则推送“this”值,如果返回 False,则推送“that”值。

感谢您的帮助:)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用 NumPy 中的where() 函数:

    df['New Column'] = np.where(df.columnA.str.match(regex), "this", "that")
    

    您可以使用其他列名代替标量:

    df['New Column'] = np.where(df.columnA.str.match(regex), df.columnB, df.columnC)
    

    【讨论】:

    • 你好@DYZ。如果要处理多种可能性而不仅仅是二元条件,我该怎么办?如何使用我自己的函数,例如 "return myfunction(df.columnA)" ?感谢您的帮助!
    • 好的,我刚刚做了一个测试,这很简单,我只需要使用参数中的列调用我的函数,它就可以工作了。 Pyhon 绝对是魔法。
    【解决方案2】:

    既然你已经得到了一系列布尔值,为什么不简单的map呢?

    df['New Column'] = list(map(lambda b : 'this' if b else 'that', df.foo.str.match('foo.')))
    

    【讨论】:

      【解决方案3】:

      编辑:

      df['New Column'] = ["this" if row.str.match(regex) else "that" for row in df.columnA]
      

      【讨论】:

        猜你喜欢
        • 2020-04-25
        • 2022-12-15
        • 1970-01-01
        • 2019-02-17
        • 2017-06-20
        • 2016-02-10
        • 2019-02-15
        • 1970-01-01
        • 2022-08-17
        相关资源
        最近更新 更多