我有一个代码,我正在修改这样的单元格: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是apd.DataFrameIBM["PNL"]是apd.Series[](方括号)调用__getitem__方法并返回一个series对象。然后调用__getitem__返回的序列的IBM["PNL"][2]方法,即[2]部分。现在还可以,即使有点混乱。当您试图分配时出现问题。IBM["PNL"][2] = 3告诉pandas分配给pd.SeriesIBM["PNL"]的第二个元素,这是"PNL"数据框内IBM列的视图。。。头晕了吗?
因此,答案是使用适当的索引器直接分配给带有IBMlocilocatiatset_value数据帧。
loc
允许您将一维数组作为索引器传递。数组可以是索引或列的切片(子集),也可以是长度等于索引或列的布尔数组。
特别注意:当一个标量索引器被传递时,loc可以分配一个新的索引或列值,这些值以前不存在。

# described by @ayhan
IBM.loc[IBM.index[2], 'PNL'] = 3

iloc
loc类似,除了位置而不是索引值。但是,不能指定新列或索引。
# described by @ayhan
IBM.iloc[2, IBM.columns.get_loc('PNL')] = 3

at
工作原理与标量索引器的loc非常相似。无法对数组索引器进行操作。可以!分配新索引和列
IBM.at[IBM.index[2], 'PNL'] = 3

iat
工作原理与iloc类似。无法在数组索引器中工作。不能!分配新的索引和列。
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3

set_value
工作原理与标量索引器的loc非常相似。无法对数组索引器进行操作。可以!分配新索引和列
IBM.set_value(IBM.index[2], 'PNL', 3)

set_value with takable=True
工作原理与iloc类似。无法在数组索引器中工作。不能!分配新的索引和列。
IBM.set_value(2, IBM.columns.get_loc('PNL'), 3, takable=True)

关于python - 如何正确修改数据框中的单元格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43968470/

10-13 01:43