2013-02-25 73 views
1

我在更改DataFrame中的整数系列时遇到问题。当我尝试将整数序列的一部分更改为另一个整数序列的等长部分时,会发生此问题。更改熊猫中的整数数据系列时的TypeError

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

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

您碰到了我们刚刚发现的这个错误。请看这里:https://github.com/pydata/pandas/issues/2746。不幸的是,这有点棘手。你想用boolean int(不需要填充)进行inplace设置。我会链接到这个例子,看看。

+0

好的,谢谢。现在我正在使用解决方法,所以它不会减慢我的速度。 – kmt 2013-02-26 17:13:56

+0

只是修正了这个问题 – Jeff 2013-03-01 23:40:32