python - 使用 df.column.str.contains 并更新 pandas 数据框列

标签 python regex pandas

我有一个包含两列的 pandas 数据框。

df= pd.DataFrame({"C": ['this is orange','this is apple','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]})

我希望能够读取此 C 列并在 D 列中返回水果的名称。所以我的思考过程是使用 df.C.str.contains 来确定某个字符串是否出现在 C 的每一行中,然后 D 相应地更新。 C 中的元素可能是非常长的字符串:例如。 “这是红色的苹果”,但我只关心“苹果”这个词是否出现在单元格中。我应该注意,我并不局限于使用 str.contains 但这对我来说似乎是最明显的路径。只是不确定如何应用它。

最终的数据框将如下所示:

df= pd.DataFrame({"C": ['this is orange','this is apple','this is pear','this is plum','this is orange'], "D": ['orange','apple','pear','plum','grapefruit']})

最佳答案

考虑这个数据框

df= pd.DataFrame({"C": ['this is orange','this is apple which is red','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]})

    C                           D
0   this is orange              0
1   this is apple which is red  0
2   this is pear                0
3   this is plum                0
4   this is orange              0

您可以使用以下代码提取水果名称,假设水果名称位于“this is”之后

df['D'] = df.C.str.extract('this is ([A-Za-z]+)\s?.*?')

你得到了

    C                           D
0   this is orange              orange
1   this is apple which is red  apple
2   this is pear                pear
3   this is plum                plum
4   this is orange              orange

对于您发布的示例数据集,可以对空间进行简单的分割并提取最后一个元素

df['D'] = df.C.str.split(' ').str[-1]

关于python - 使用 df.column.str.contains 并更新 pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593948/

相关文章:

python - txt 文件的字数统计并输出到文件

python - 为什么 Python 使用以下代码知道答案按字母顺序排列是正确的?

python - Pandas 中具有 NaN 值的子集列

regex - 带正则表达式的 CASE : "set-valued function called in context that cannot accept a set"

Python:正则表达式从单词中剥离模式并打印其余部分

python - pandas 中 merge() 和 concat() 的区别

python-3.x - pandas 中的列串联

python - 在 Python 中使用正则表达式从字符串中提取坐标

python - 通过 Python 在 Midi 的特定时间写笔记

正则表达式匹配 <A>、<BB>、<CCC> 但不匹配 <ABC> 等标签