首页 > 解决方案 > Pandas 警告 SettingWithCopyWarning:试图在 DataFrame 中的切片副本上设置值

问题描述

我似乎无法理解为什么我从下面的熊猫代码中收到警告:我正在尝试使用以下代码将 titanic.csv 数据集中的“性别”列转换为数字:

from sklearn import preprocessing
label_encoding = preprocessing.LabelEncoder()
titanic_df['Sex'] =label_encoding.fit_transform(titanic_df['Sex'].astype(str))
titanic_df.head()

我收到这个警告:

<ipython-input-41-45071618b7c1>:4: 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
  titanic_df['Sex'] =label_encoding.fit_transform(titanic_df['Sex'].astype(str))

如何格式化代码以避免出错?

标签: pythonpandasscikit-learnjupyter-notebook

解决方案


推荐阅读