2016-06-15 3 views
2

質問によって選択欄はprobaly非常にダムですが、私は私の脳は、N列のpd.dataframeありパンダデータフレームとto_numeric:インデックス

何をすべきかを考え出す傷つけます。私はdf['a'] = pd.to_numeric(df['a'])のような(列名の参照によってそれを行ったが指標(のようなdf[1] = pd.to_numeric(df[1])で立ち往生してきた数値にすべての値を変換して、私のdataframe

にその列を書き換え、その後、列のインデックスで参照する、いくつかの列を選択する必要がありますdataframeコラム参照に、このような状況で正しい方法は何

(のpython 2.7)

答えて

3

あなたはその後、選択列に対してixを使用することができapplyto_numeric:?

import pandas as pd 

df = pd.DataFrame({1:['1','2','3'], 
        2:[4,5,6], 
        3:[7,8,9], 
        4:['1','3','5'], 
        5:[5,3,6], 
        6:['7','4','3']}) 

print (df) 
    1 2 3 4 5 6 
0 1 4 7 1 5 7 
1 2 5 8 3 3 4 
2 3 6 9 5 6 3 

print (df.dtypes) 
1 object 
2  int64 
3  int64 
4 object 
5  int64 
6 object 
dtype: object 

print (df.columns) 
Int64Index([1, 2, 3, 4, 5, 6], dtype='int64') 
cols = [1,4,6]  
df.ix[:, cols] = df.ix[:, cols].apply(pd.to_numeric) 

print (df) 
    1 2 3 4 5 6 
0 1 4 7 1 5 7 
1 2 5 8 3 3 4 
2 3 6 9 5 6 3 

print (df.dtypes) 
1 int64 
2 int64 
3 int64 
4 int64 
5 int64 
6 int64 
dtype: object 

列はstrings、ないint(それはintのように見える)listcolsの番号に''を追加している場合:

import pandas as pd 

df = pd.DataFrame({'1':['1','2','3'], 
        '2':[4,5,6], 
        '3':[7,8,9], 
        '4':['1','3','5'], 
        '5':[5,3,6], 
        '6':['7','4','3']}) 

#print (df) 

#print (df.dtypes) 

print (df.columns) 
Index(['1', '2', '3', '4', '5', '6'], dtype='object') 

#add `''` 
cols = ['1','4','6'] 
#1. ix: supports mixed integer and label based access  
df.ix[:, cols] = df.ix[:, cols].apply(pd.to_numeric) 

#2. loc: only label based access 
# df.loc[:, cols] = df.loc[:, cols].apply(pd.to_numeric) 

#3. iloc: for index based access 
# cols = [i for i in range(len(df.columns))] 
# df.iloc[:, cols].apply(pd.to_numeric) 

print (df) 
    1 2 3 4 5 6 
0 1 4 7 1 5 7 
1 2 5 8 3 3 4 
2 3 6 9 5 6 3 

print (df.dtypes) 
1 int64 
2 int64 
3 int64 
4 int64 
5 int64 
6 int64 
dtype: object 
+0

ありがとうございました。しかし、intを持つ非intヘッダーで列を参照する方法はありますか? 'cols = [6]で' Index '([' 1 '、' 2 '、' 3 '、' 4 '、' 5 '、' k ']、dtype =' object ') 'の第6列を参照すると、 '? –

+0

はい、あなたは['iloc'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html)を使うことができます - そうです。6. columnsは' df.iloc [ 、5] '(Python count from 0) – jezrael

+0

うまく働いて、ありがとう! –

関連する問題