2014-02-26 81 views
6

我的问题是,添加行到数据帧改变D型细胞列组成:添加行到大熊猫数据帧改变D型细胞

>>> from pandas import DataFrame 
>>> df = DataFrame({'a' : range(10)}, dtype='i4') 
>>> df 
    a 
0 0 
1 1 
2 2 
3 3 
4 4 
5 5 
6 6 
7 7 
8 8 
9 9 

[10 rows x 1 columns] 

我特别指定D型细胞是INT32(即,“6-14”),如可可以看出:

>>> df.dtypes 
a int32 
dtype: object 

然而,加入了行更改d型到float64:

>>> df.loc[10] = 99 

>>> df 
    a 
0 0 
1 1 
2 2 
3 3 
4 4 
5 5 
6 6 
7 7 
8 8 
9 9 
10 99 

[11 rows x 1 columns] 

>>> df.dtypes 
a float64 
dtype: object 

我已经试过指定d我添加的值的类型:

>>> import numpy as np 
>>> df = DataFrame({'a' : np.arange(10, dtype=np.int32)}) 

>>> df.dtypes 
a int32 
dtype: object 

>>> df.loc[10] = np.int32(0) 

>>> df.dtypes 
a float64 
dtype: object 

但是这也行不通。有没有解决方案,没有使用返回新对象的函数?

回答

7

扩展分两阶段完成,首先将nan放置在该列中,然后分配它,这就是为什么它被强制。我会把它放在bug /增强列表上。它有点不平凡。

这是一个解决方法,使用append。

In [14]: df.append(Series(99,[10],dtype='i4').to_frame('a')) 
Out[14]: 
    a 
0 0 
1 1 
2 2 
3 3 
4 4 
5 5 
6 6 
7 7 
8 8 
9 9 
10 99 

[11 rows x 1 columns] 

In [15]: df.append(Series(99,[10],dtype='i4').to_frame('a')).dtypes 
Out[15]: 
a int32 
dtype: object 

的错误的一个问题/增强这样做自动的:https://github.com/pydata/pandas/issues/6485

+1

对于任何人谁愿意上为什么NaN被强迫它点颜色浮动:http://pandas.pydata.org/pandas -docs/stable/gotchas.html#support-for-integer-na (我被这个难住了) – fantabolous