Pandas 数据框和 to_numeric:按索引选择列

问题描述 投票:0回答:2

这个问题可能非常愚蠢,但我不知道该怎么做,伤了我的大脑

有一个

pd.dataframe
有 N 列。我需要选择一些列,通过列的索引引用,然后将所有值转换为数字并在我的
dataframe

中重写该列

我已经通过列名称引用完成了它(如

df['a'] = pd.to_numeric(df['a'])
但坚持使用索引(如
df[1] = pd.to_numeric(df[1])

在这种情况下,

dataframe
列引用的正确方法是什么? (蟒蛇2.7)

python pandas dataframe numeric
2个回答
4
投票

您可以使用

iloc
选择列,然后使用
apply
to_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.iloc[:, cols] = 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

如果列是

strings
,而不是
int
(但看起来像
int
),请将
''
添加到
list
cols
中的数字:

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. loc: only label based access
# df.loc[:, cols] = df.loc[:, cols].apply(pd.to_numeric)

#2. iloc: for index based access
# cols = [1,4,6]
# 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

© www.soinside.com 2019 - 2024. All rights reserved.