使用Regex条件在Pandas DataFrame中创建新列 [英] Use Regex condition to create a new column in a Pandas DataFrame
本文介绍了使用Regex条件在Pandas DataFrame中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的问题。
我知道如何基于RegEx创建布尔列,例如:
I know how to create a boolean column based on RegEx, like this:
df['New Column'] = df.columnA.str.match(regex)
在此示例中,新列将包含True或False值。
In this example, 'New Column' will be contain True or False values.
但是如果要使用该怎么办一个条件,说如果我的RegEx返回true,则推 this值,如果它返回False,则推 that值。
But how do I do if I want to use a condition to say "If my RegEx returns true, push "this" value, and if it returns False, then push "that" value.
感谢您的帮助:)
推荐答案
您可以使用NumPy中的 where()
函数:
You can use the where()
function from NumPy:
df['New Column'] = np.where(df.columnA.str.match(regex), "this", "that")
您可以使用其他列名代替标量:
You can use other column names instead of the scalars:
df['New Column'] = np.where(df.columnA.str.match(regex), df.columnB, df.columnC)
这篇关于使用Regex条件在Pandas DataFrame中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文