首页 > 解决方案 > np.where 的语法替换列值

问题描述

我能够使用 np.where() 成功地将 Yes\No 值替换为 1\0。

但是,无论我使用什么语法,我总是会收到两个 SettingWithCopyWarning 警告之一。我想知道正确的语法,这样我就可以避免警告。

我尝试了三种不同的方法。他们都工作,但他们都产生警告:

df['Churn'] = np.where(df['Churn'].values == 'Yes', 1, 0)
df['Churn'] = np.where(df.loc[:, 'Churn'].values == 'Yes', 1, 0)
C:/Users/Mark/PycharmProjects/main/main.py:62: SettingWithCopyWarning: 
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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['Churn'] = np.where(df['Churn'].values == 'Yes', 1, 0)
df.loc[:, 'Churn'] = np.where(df.loc[:, 'Churn'].values == 'Yes', 1, 0)
C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexing.py:966: SettingWithCopyWarning: 
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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[item] = s

标签: python-3.xpandasnumpy

解决方案


推荐阅读