使用Regex条件在Pandas DataFrame中创建新列


问题内容

这是我的问题。

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

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

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

但是,如果我想使用条件说“如果我的RegEx返回true,则推“ this”值,如果返回False,然后推“ that”值,该怎么办。

感谢您的帮助 :)


问题答案:

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

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)