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
作品。
有什麼建議嗎?
謝謝!
好的,謝謝。現在我正在使用解決方法,所以它不會減慢我的速度。 – kmt 2013-02-26 17:13:56
只是修正了這個問題 – Jeff 2013-03-01 23:40:32