更改pandas中的整数数据系列时的TypeError

时间:2013-02-25 22:39:13

标签: pandas

我在更改DataFrame中的整数系列时遇到问题。当我尝试将整数系列的一部分更改为另一个整数系列的等长部分时,会出现问题。

这是重现我的问题的简单代码:

import pandas as pd
import numpy as np
a = np.arange(10,dtype=np.int)
b = a**2 - 10*a + 12
df = pd.DataFrame({'a':a,'b':b,'a_float':a.astype(np.float),
                   'b_float':b.astype(np.float)})
print df.dtypes

a         int64
a_float   float64
b         int64
b_float   float64

cond = df.b<0
df.b[cond] = 7  #works, as expected
df.b_float[cond] = df.a_float[cond] #works
df.b[cond] = df.a[cond] #gives a TypeError

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-518b5957d002> in <module>()
----> 1 df.b[cond] = df.a[cond]

Users/kmt/Envs/scilab/lib/python2.7/site-packages/pandas-0.11.0.dev_eb3134f-py2.7-macosx-     10.7-x86_64.egg/pandas/core/series.pyc in __setitem__(self, key, value)
    740         if _is_bool_indexer(key):
    741             key = _check_bool_indexer(self.index, key)
--> 742             self.where(~key,value,inplace=True)
    743         else:
    744             self._set_with(key, value)

/Users/kmt/Envs/scilab/lib/python2.7/site-packages/pandas-0.11.0.dev_eb3134f-py2.7-macosx-    10.7-x86_64.egg/pandas/core/series.pyc in where(self, cond, other, inplace)
    681             raise ValueError('Length of replacements must equal series length')
    682 
--> 683         np.putmask(ser, ~cond, other)
    684 
    685         return None if inplace else ser

TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule  'safe'

请注意

b[cond] = a[cond]
df.b = b

作品。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你遇到了我们刚刚发现的这个bug。见这里:https://github.com/pydata/pandas/issues/2746。不幸的是,这有点棘手。你想用布尔int(不需要填充)进行inplace设置。我将链接到此示例并查看。