我有一个包含两列的 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/