【发布时间】:2017-08-10 21:48:00
【问题描述】:
这是我的问题。
我知道如何基于 RegEx 创建一个布尔列,如下所示:
df['New Column'] = df.columnA.str.match(regex)
在此示例中,“新列”将包含 True 或 False 值。
但是如果我想使用一个条件来表示“如果我的 RegEx 返回 true,则推送“this”值,如果返回 False,则推送“that”值。
感谢您的帮助:)
【问题讨论】:
这是我的问题。
我知道如何基于 RegEx 创建一个布尔列,如下所示:
df['New Column'] = df.columnA.str.match(regex)
在此示例中,“新列”将包含 True 或 False 值。
但是如果我想使用一个条件来表示“如果我的 RegEx 返回 true,则推送“this”值,如果返回 False,则推送“that”值。
感谢您的帮助:)
【问题讨论】:
您可以使用 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)
【讨论】:
既然你已经得到了一系列布尔值,为什么不简单的map呢?
df['New Column'] = list(map(lambda b : 'this' if b else 'that', df.foo.str.match('foo.')))
【讨论】:
编辑:
df['New Column'] = ["this" if row.str.match(regex) else "that" for row in df.columnA]
【讨论】: