简体   繁体   English

将pandas Dataframe转换为float

[英]Converting pandas Dataframe to float

I cannot convert data types in my dataframe to float from string (they are numerical values as string or empty strings): 我无法将数据框中的数据类型转换为从字符串浮点型(它们是字符串或空字符串形式的数值):

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

What am i doing wrong here? 我在这里做错了什么?

Hypothetical DataFrame: 假设数据框:

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

Current data types: 当前数据类型:

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

Convert the entire df columns to numeric: 将整个df列转换为数字:

df = df.apply(pd.to_numeric)

Result: 结果:

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

Convert only select columns to numeric: 仅将选择列转换为数字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM