python - 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))
如何格式化代码以避免出错?
解决方案
推荐阅读
- javascript - response.text 在构建 react-native 应用程序时不是一个函数
- arrays - 谷歌电子表格查询范围将项目向右
- javascript - 获取对表的 td 输入的 Ajax 响应
- python - opencv 人脸检测从每张图片中只保存一张脸,即使有几张脸
- react-native - 当滚动视图在当前屏幕上时,反应导航抽屉不会通过滑动手势打开
- curl - SendGrid cURL 响应返回空,但电子邮件发送
- java - Avalara:由于 JSON 转换异常,无法从 TransactionBuilder 创建 TransactionModel
- string - pandas 将数据帧与字符串变量合并;尽管完全匹配,但适用于大多数 obs 但不适用于其他人
- python - 如何根据另一列中的值更新一列中的值?(获取 KeyError:“[列]中没有...”
- proxy - 出站请求的缓存服务