如果另一列包含字符串,请替换pandas中的一列

时间:2018-06-26 21:07:26

标签: python python-3.x pandas dataframe machine-learning

我有两列newlabels和newlabels_tobeReplaced。如果newlabels句子中包含单词'trifurcation',则应将newlabels_tobeReplaced替换为'trifurcation' 我有以下代码

df_new.loc[df_new.newlabels.str.contains('trifurcation'),'newlabels_tobeReplaced'] = 'trifurcation'

但是,我收到此错误:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s

任何想法,如何获得正确的结果。 问题在于新标签的值如下:“波形提示在足踝水平静息时发生左下肢轻度远端缺血的三叉神经病变疾病。”

1 个答案:

答案 0 :(得分:2)

您可以通过将df_new产生的副本重新分配给assign来解决该警告

df_new = df_new.assign(
    newlabels_tobeReplaced=
    lambda d: d['newlabels_tobeReplaced'].mask(
        d.newlabels.str.contains('trifurcation'), 'trifurcation'
    )
)