2013-07-21 58 views
5

我按照建議here來更改熊貓數據框的列數據類型。但是,如果我通過索引號而不是列名來引用列,它似乎不起作用。有沒有辦法做到這一點?熊貓:無法更改列數據類型

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]: 

回答

3

做這樣的

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 

通過分配與右側的一系列複製數據更改類型根據需要,所以我認爲這應該在理論上工作,但我懷疑這是一個非常模糊的錯誤,防止對象dtype更改爲真實 (意思是int/float)dtype。現在應該可能籌集。

繼承人問題追蹤此:https://github.com/pydata/pandas/issues/4312