我有一个修改单元格的代码:IBM["PNL"][2]=3
。它起作用了,但它显示了一个警告:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
从我在文章中所读到的内容来看,修改值的正确方法应该是IBM.loc[2,"PNL"]=3
。但是,这对我不起作用,它失败了,并出现以下错误:
Traceback (most recent call last):
File "<ipython-input-25-10debbad977d>", line 1, in <module>
IBM_dataframe.loc[0,"PNL"]
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1310, in __getitem__
return self._getitem_tuple(key)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 796, in _getitem_tuple
return self._getitem_lowerdim(tup)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 922, in _getitem_lowerdim
section = self._getitem_axis(key, axis=i)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1482, in _getitem_axis
self._has_valid_type(key, axis)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1409, in _has_valid_type
key = self._convert_scalar_indexer(key, axis)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 196, in _convert_scalar_indexer
return ax._convert_scalar_indexer(key, kind=self.name)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\tseries\base.py", line 591, in _convert_scalar_indexer
self._invalid_indexer('index', key)
File "C:\Users\menkaur\Anaconda2\lib\site-packages\pandas\indexes\base.py", line 1284, in _invalid_indexer
kind=type(key)))
TypeError: cannot do index indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2] of <type 'int'>
现在,我很困惑
我做错什么了?你知道吗
假设
IBM
是pd.DataFrame
,IBM["PNL"]
是pd.Series
。[]
(方括号)调用__getitem__
方法并返回一个series对象。然后对返回IBM["PNL"][2]
的序列调用__getitem__
方法,即[2]
部分。现在还可以,即使有点混乱。当您试图分配给它时,出现了问题。IBM["PNL"][2] = 3
告诉pandas
分配给pd.Series
IBM["PNL"]
的第二个元素,这是IBM
数据帧内"PNL"
列的视图。。。头晕了吗?你知道吗因此,答案是使用适当的索引器将
loc
、iloc
、at
、iat
或set_value
直接分配给IBM
数据帧。你知道吗^{}
允许您将一维数组作为索引器传递。数组可以是索引或列的片(子集),也可以是长度等于索引或列的布尔数组。你知道吗
特别注意:当传递标量索引器时,
loc
可以指定以前不存在的新索引或列值。你知道吗^{}
类似于
loc
,除了位置而不是索引值。但是,您不能指定新的列或索引。你知道吗^{}
对于标量索引器,其工作原理与
loc
非常相似。无法对数组索引器进行操作。可以!指定新索引和列^{}
类似于
iloc
。不能在数组索引器中工作。不行!指定新索引和列。你知道吗^{}
对于标量索引器,其工作原理与
loc
非常相似。无法对数组索引器进行操作。可以!指定新索引和列^{} with ^{}
类似于
iloc
。不能在数组索引器中工作。不行!指定新索引和列。你知道吗既然
.ix
已被弃用,您有两种选择:这是基于标签的索引。因为您需要标签,但是您有位置,所以可以使用
IBM.index[2]
返回标签。或者这是基于位置的索引。要获得列
PNL
的位置,可以使用get_loc
。你知道吗错误是因为您尝试对行使用基于位置的索引,而对列使用基于标签的索引。
.ix
被设计用来处理这种情况,但它已被弃用。Here是@jezrael注意到的细节。你知道吗相关问题 更多 >
编程相关推荐