python - 替换 Python 数据框特定列的特定值会引发“SettingWithCopyWarning”
问题描述
此代码的执行工作:
import pandas as pd
df = pd.DataFrame({'name':["Adam", "Sarah", "Tom", "Sarah", "Adam", "Tom", "Will"], 'score':[1,16,2,32,11,9,50]})
print(df)
colName = 'score'
df[colName][df[colName] <= 10] = 1
df[colName][(df[colName] > 10) & (df[colName] <= 20)] = 11
df[colName][df[colName] > 20] = 21
print(df)
...但抛出此警告:
test.py:9:SettingWithCopyWarning:试图在 DataFrame 中的切片副本上设置值
请参阅文档中的注意事项:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][df[colName] < = 10] = 1 test.py:10: SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置值
请参阅文档中的警告:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][(df[colName] > 10) & (df[colName] <= 20)] = 11 test.py:11: SettingWithCopyWarning: 试图在数据帧的切片副本上设置值
请参阅文档中的注意事项:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][df[colName] > 20] = 21
我想这是深/浅复制的问题?但是我该如何解决呢?必须有一种简单易读的方法来进行如此简单的操作吗?
编辑:它适用于:
df.loc[df[colName] <= 10, colName] = 1
...但这有点不合逻辑,因为 colName 作为第二个参数是违反直觉的...
解决方案
试试下面的代码,希望这会有所帮助。
import pandas as pd
import numpy as np
df = pd.DataFrame({'name':["Adam", "Sarah", "Tom", "Sarah", "Adam", "Tom", "Will"], 'score':[1,16,2,32,11,9,50]})
print(df)
colName = 'score'
df[colName] = np.where(df[colName] <= 10, 1, df[colName])
df[colName] = np.where((df[colName] > 10) & (df[colName] <= 20), 11 , df[colName])
df[colName] = np.where(df[colName] > 20, 21 , df[colName])
print(df)
输出将是:
name score
0 Adam 1
1 Sarah 16
2 Tom 2
3 Sarah 32
4 Adam 11
5 Tom 9
6 Will 50
****NEW*********
name score
0 Adam 1
1 Sarah 11
2 Tom 1
3 Sarah 21
4 Adam 11
5 Tom 1
6 Will 21
这不会给出任何警告,因为您没有处理数据帧的任何部分,而是使用条件子句并更新列的值。
推荐阅读
- node.js - 我如何使用上传按钮将图像(使用 NodeJs)上传到烧瓶中的图像分类器 api 或在 XYZ.com 上运行的图像分类器
- azure - 如何解决 Microsoft Graph API 的“暂时性错误”?
- android - 如何添加android.support.v7.widget.Toolbar
- react-native - React Native : Expo Start Gives EIO: i/o error, read
- mysql - MYSQL ID 不按顺序
- java - 我真的需要一个新的 Solr 系列吗?
- r - 通过分配不同的矩阵来计算字符的频率
- logging - 流利的不尊重日志轮换
- stenciljs - 在 stencil.js 中创建供内部使用的“私有”组件
- agda - _≡⟨_⟩_ Agda 标准库在哪里?