pandas 使用混合列类型增加数据框的单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19777751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:18:24  来源:igfitidea点击:

pandas increment cell value of dataframe with mixed column types

pythonpandas

提问by will

I'd like to increment a cell of a dataframe:

我想增加数据帧的一个单元格:

from pandas import DataFrame
foo = DataFrame([[1,'a'],[2,'b'],[3,'c']],columns=['a','z'])
foo.ix[0,['a']] += 1

which gives the following error:

这给出了以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-141-cf9b905bd544> in <module>()
      1 foo = DataFrame([[1,'a'],[2,'b'],[3,'c']],columns=['a','z'])
----> 2 foo.ix[0,['a']] += 1

/home/ubuntu/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in __setitem__(self, key, value)
     86             indexer = self._convert_to_indexer(key)
     87 
---> 88         self._setitem_with_indexer(indexer, value)
     89 
     90     def _has_valid_tuple(self, key):

/home/ubuntu/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _setitem_with_indexer(self, indexer, value)
    156                 # we have an equal len list/ndarray
    157                 elif len(labels) == 1 and (
--> 158                     len(self.obj[labels[0]]) == len(value) or len(plane_indexer[0]) == len(value)):
    159                     setter(labels[0], value)
    160 

TypeError: object of type 'int' has no len()

Even though the following willwork:

即使以下内容有效:

foo = DataFrame([[1,4],[2,5],[3,6]],columns=['a','z'])
foo.ix[0,['a']] += 1

Which leads me to believe the issue is different column types.

这让我相信问题是不同的列类型。

How can I increment the cell value of the first dataframe?

如何增加第一个数据帧的单元格值?

回答by Jeff

In [1]: foo = DataFrame([[1,'a'],[2,'b'],[3,'c']],columns=['a','z'])

In [3]: foo
Out[3]: 
   a  z
0  1  a
1  2  b
2  3  c

In [4]: foo.dtypes
Out[4]: 
a     int64
z    object
dtype: object

In [5]: foo.ix[0,'a'] += 1

In [6]: foo
Out[6]: 
   a  z
0  2  a
1  2  b
2  3  c