- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在一个类的方法中,我使用了这个语句:
self.__datacontainer.iloc[-1]['c'] = value
这样做我得到了“设置复制警告:试图在 DataFrame 的切片副本上设置一个值”
现在我尝试重现此错误并编写以下简单代码:
import pandas, numpy
df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))
df.iloc[-1]['C'] = 3
没有错误。为什么我在第一条语句中出现错误,而在第二条语句中却没有?
最佳答案
链式索引
作为documentation以及本网站上的其他几个答案([1]、[2])建议,链索引被认为是不好的做法,应该避免。
因为似乎没有一种使用基于整数位置的索引(即.iloc
)进行赋值而不违反链索引规则(截至pandas v0.23.4
),建议尽可能使用基于标签的索引(即.loc
)进行分配。
但是,如果您确实需要按行号访问数据,您可以
df.iloc[-1, df.columns.get_loc('c')] = 42
或
df.iloc[[-1, 1], df.columns.get_indexer(['a', 'c'])] = 42
Pandas 行为怪异
据我了解,您在尝试人为重现错误时收到警告是完全正确的。
到目前为止我发现它取决于数据框的构造方式
df = pd.DataFrame({'a': [4, 5, 6], 'c': [3, 2, 1]})
df.iloc[-1]['c'] = 42 # no warning
df = pd.DataFrame({'a': ['x', 'y', 'z'], 'c': ['t', 'u', 'v']})
df.iloc[-1]['c'] = 'f' # no warning
df = pd.DataFrame({'a': ['x', 'y', 'z'], 'c': [3, 2, 1]})
df.iloc[-1]['c'] = 42 # SettingWithCopyWarning: ...
似乎 pandas(至少 v0.23.4
)在链分配时以不同方式处理混合类型和单一类型的数据帧 [3]
def _check_is_chained_assignment_possible(self):
"""
Check if we are a view, have a cacher, and are of mixed type.
If so, then force a setitem_copy check.
Should be called just near setting a value
Will return a boolean if it we are a view and are cached, but a
single-dtype meaning that the cacher should be updated following
setting.
"""
if self._is_view and self._is_cached:
ref = self._get_cacher()
if ref is not None and ref._is_mixed_type:
self._check_setitem_copy(stacklevel=4, t='referant',
force=True)
return True
elif self._is_copy:
self._check_setitem_copy(stacklevel=4, t='referant')
return False
这对我来说真的很奇怪,虽然我不确定它是否不是预期的。
但是,有一个旧的bug具有类似的行为。
更新
根据developers上述行为是预期的。
关于python - 为什么 iloc() 的一种使用给出了 SettingWithCopyWarning,而另一种却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53806570/
我正在研究 Pandas 并研究汽车(一个 csv 文件)。我运行了以下命令: 1) cars.iloc[[3, 0]] Out[2]: cars_per_cap country dri
我无法使用 x.iloc[1]['x']=16 将 np.nan 的值更改为 16,但我可以使用 x['x'].iloc[1]=16 更改它。为什么?这两个表达式有什么区别? x = pd.DataF
我想对列中的值使用 iloc。 df1 = pd.DataFrame({'col1': ['1' ,'1','1','2','2','2','2','2','3' ,'3','3'],
所以我想选择数据帧的前 10 行,但通过特定的列名称(例如“价格”)。显然我可以这样做: df.iloc[0:10]['价格'] 但我想避免链式索引。有办法做到这一点吗?我无法使用 LOC,因为没有编
我有一个ProductDf,它有同一产品的多个版本。我想过滤产品的最后一次迭代。所以我这样做了如下: productIndexDf= ProductDf.groupby('productId').ap
这里是新手。 我正在尝试学习 Python 并使用数据集,我有点陷入工作的深渊。该语言显然非常强大,但与我以前体验过的任何其他语言都截然不同。 我需要以下方面的一些澄清/帮助/解释。 部分算法代码 h
我掉了前两个 栏目 在下面的代码中使用 iloc 方法没有任何问题。 eng_df.drop(eng_df.iloc[:,:2] , axis=1, inplace=True) 但我试图删除第一个 行
我可以使用:iloc[:, [1,2,3,27, 4:27] 我想按列索引对列重新排序并在输出中包含所有列 最佳答案 是的,你可以,但你需要构建一个没有切片的索引列表。 Numpy 有一个漂亮的 he
我可以使用:iloc[:, [1,2,3,27, 4:27] 我想按列索引对列重新排序并在输出中包含所有列 最佳答案 是的,你可以,但你需要构建一个没有切片的索引列表。 Numpy 有一个漂亮的 he
首先我应该说,我对 pandas 和 numpy(以及一般的机器学习)还很陌生。 我正在尝试学习一些基本的机器学习算法并正在做线性回归。我已经使用 matlab 完成了这个问题,但想尝试用 pytho
我在使用 .loc/.iloc 作为循环的一部分时遇到一些问题。这是我的代码的简化版本: INDEX=['0', '1', '2', '3', '4'] COLUMNS=['A','B','C'] d
鉴于下面的数据框,我想选择 A 列、D 列到 F 列。 import numpy as np import pandas as pd df = pd.DataFrame(np.random.randi
现在正在浏览 Kaggle 教程,虽然我通过查看输出和阅读文档了解了它的作用的基本概念,但我认为我需要确认这里发生的事情: predictors = ["Pclass", "Sex", "Age",
假设我有以下具有相同列名的 DataFrame test = pd.DataFrame([[1, 2, 3, np.nan, np.nan], [1, 2,
我想通过 iloc 更改我的 DataFrame 中某些列的数据类型。但是当我尝试这个时,dtype 没有改变(它仍然是对象): import pandas as pd names = ['sepal
我正在尝试拆分包含 1500 多家公司股票数据的 CSV 文件。第一列包含日期,后续列包含公司数据。 当我使用 iloc 功能将 CSV 文件拆分为包含较少列的较小文件时,它会生成一个更大的文件。 数
我从 pandas DataFrame 中选择 2 - end 列,iloc 为 d=c.iloc[:,2:] 现在如何将条件应用于此选择?例如,如果 column1==1。 最佳答案 您可以使用 D
我有一个 32 列的 df df.shape (568285, 32) 我正在尝试以特定方式重新排列列,并使用 iloc 删除第一列 df = df.iloc[:,[31,[1:23],24,25,
pandas的DataFrame对象,本质上是二维矩阵,跟常规二维矩阵的差别在于前者额外指定了每一行和每一列的名称。这样内部数据抽取既可以用“行列名称(对应.loc[]方法)”,也可以用“矩阵下标(
我有一个包含贡献者 ID 和贡献者消息的数据集。我想检索所有带有相同消息的样本,例如,contributor_message == '我支持这个提议,因为......'。 我使用 data.loc[d
我是一名优秀的程序员,十分优秀!