将pandas Dataframe转换为float

问题描述 投票:1回答:1

我无法将我的数据框中的数据类型转换为从字符串浮动(它们是数值为字符串或空字符串):

calcMeanPrice_df = dessertApples_df.iloc[:, 5:17]      #slice of columns

for col  in calcMeanPrice_df:                          #iterate columns
    pd.to_numeric(col, errors = 'coerce')              #attempt to convert to numeric

calcMeanPrice_df.dtypes                                #return data column types

Out[21]:
4     object
5     object
6     object
7     object
8     object
9     object
10    object
11    object
12    object
13    object
14    object
15    object
dtype: object

我在这做错了什么?

python python-3.x pandas dataframe
1个回答
4
投票

假设数据框架:

df = pd.DataFrame({'a':['5','10'], 'b':['9','7']})

目前的数据类型:

In [391]: df.dtypes
Out[391]: 
a    object
b    object

将整个df列转换为数字:

df = df.apply(pd.to_numeric)

结果:

In [393]: df.dtypes
Out[393]: 
a    int64
b    int64

仅将选择列转换为数字:

In [396]: df = pd.DataFrame({'a':['5','10'], 'b':['9','7']})
In [397]: df['a'] = df['a'].apply(pd.to_numeric)
In [398]: df.dtypes
Out[398]: 
a     int64
b    object
© www.soinside.com 2019 - 2024. All rights reserved.