我有两个列,分别是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 insteadSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copyself.obj[item] = s
有什么办法可以得到正确的结果吗?问题在于newlabels列包含类似这样的值:“Waveforms suggest trifucation disease with mild distal ischemia of left lower extremity at rest at level of ankle.”
回答:
你可以通过使用assign
方法重新赋值给df_new
来避免这个警告
df_new = df_new.assign( newlabels_tobeReplaced= lambda d: d['newlabels_tobeReplaced'].mask( d.newlabels.str.contains('trifurcation'), 'trifurcation' ))