python - Pandas 增加具有混合列类型的数据框的单元格值

标签 python pandas

我想增加数据框的单元格:

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

出现以下错误:

---------------------------------------------------------------------------
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()

即使以下工作:

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

这让我相信问题出在不同的列类型上。

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

最佳答案

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

关于python - Pandas 增加具有混合列类型的数据框的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19777751/

相关文章:

python - Pandas 分组并按索引计数排序

模板化的 Python 文档字符串

python - 打印具有给定值的行

python - 如何使用 python 仅从 CSV 文件中抓取某些 URL?

python - 是否可以在 python 中创建图排列?

python - 创建一个列,该列为另一行的更改增加值

python - 如何模拟异步协程?

python - 模拟 Excel sumifs/多标准索引与 python/pandas 中的数据帧匹配

python - 如何使用GOOGLE作为pandas数据阅读器的数据源?

python-3.x - Python - 多个Excel工作表中每天的总和