熊猫:无法更改列数据类型

时间:2013-07-21 23:51:25

标签: python pandas

我正在遵循建议here来更改pandas数据帧的列数据类型。但是,如果我按索引号而不是列名引用列,它似乎不起作用。有没有办法正确地做到这一点?

In [49]: df.iloc[:, 4:].astype(int)
Out[49]: 
&ltclass 'pandas.core.frame.DataFrame'&gt
Int64Index: 5074 entries, 0 to 5073
Data columns (total 3 columns):
5    5074  non-null values
6    5074  non-null values
7    5074  non-null values
dtypes: int64(3) 

In [50]: df.iloc[:, 4:] = df.iloc[:, 4:].astype(int)

In [51]: df
Out[51]: 
&ltclass 'pandas.core.frame.DataFrame'&gt
Int64Index: 5074 entries, 0 to 5073
Data columns (total 7 columns):
1    5074  non-null values
2    5074  non-null values
3    5074  non-null values
4    5074  non-null values
5    5074  non-null values
6    5074  non-null values
7    5074  non-null values
dtypes: object(7) 

In [52]: 

1 个答案:

答案 0 :(得分:2)

这样做

In [49]: df = DataFrame([['1','2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))

In [50]: df
Out[50]: 
   A  B  C   D  E  F    G
0  1  2  3  .4  5  6  foo

In [51]: df.dtypes
Out[51]: 
A     object
B     object
C     object
D     object
E      int64
F    float64
G     object
dtype: object

需要逐个分配列

In [52]: for k, v in df.iloc[:,0:4].convert_objects(convert_numeric=True).iteritems():
    df[k] = v
   ....:     

In [53]: df.dtypes
Out[53]: 
A      int64
B      int64
C      int64
D    float64
E      int64
F    float64
G     object
dtype: object

转换对象通常是正确的,所以最容易做到这一点

In [54]: df = DataFrame([['1','2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))

In [55]: df.convert_objects(convert_numeric=True).dtypes
Out[55]: 
A      int64
B      int64
C      int64
D    float64
E      int64
F    float64
G     object
dtype: object

通过df.iloc[:,4:]分配右侧的系列根据需要复制数据更改类型,所以我认为这应该在理论上有效,但我怀疑这是一个非常模糊的错误,阻止了对象dtype从更改为 real (意味着int / float)dtype。现在应该提高。

这是跟踪此问题的问题:https://github.com/pydata/pandas/issues/4312