在pandas中,如果另一列包含特定字符串则替换某列

我有两个列,分别是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'    ))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注