gpt4 book ai didi

python - 将 Pandas 数据框转换为 float

转载 作者:行者123 更新时间:2023-11-28 21:38:36 26 4
gpt4 key购买 nike

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

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

我做错了什么?

最佳答案

假设的数据框:

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

关于python - 将 Pandas 数据框转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com