gpt4 book ai didi

pandas - 将多个数据类型转换为 float ?

转载 作者:行者123 更新时间:2023-12-05 04:10:47 25 4
gpt4 key购买 nike

使用 pandas,如何将数据类型为“object”的多个 dateframe 列转换为 float。

df = pd.DataFrame()
df["A"] = ["123.45","34","-9","4","5"]
df["B"] = ["-9.07","5.4","3","1.0","4.5557"]
df["C"] = ["34","34.98","-9.654","45","6"]
df["D"] = ["AAA","AVF","ERD","DFE","SFE"]

使用这个会给出 AttributeError: 'list' object has no attribute 'apply':

[df["A"],df["B"],df["C"]] = [df["A"],df["B"],df["C"]].apply(pd.to_numeric, errors='coerce')

最佳答案

df = df.apply(pd.to_numeric, errors='coerce')

In [119]: df
Out[119]:
A B C
0 123.45 -9.0700 34.000
1 34.00 5.4000 34.980
2 -9.00 3.0000 -9.654
3 4.00 1.0000 45.000
4 5.00 4.5557 6.000

In [120]: df.dtypes
Out[120]:
A float64
B float64
C float64
dtype: object

更新:

In [128]: df[df.columns.drop('D')] = df[df.columns.drop('D')].apply(pd.to_numeric, errors='coerce')

In [129]: df
Out[129]:
A B C D
0 123.45 -9.0700 34.000 AAA
1 34.00 5.4000 34.980 AVF
2 -9.00 3.0000 -9.654 ERD
3 4.00 1.0000 45.000 DFE
4 5.00 4.5557 6.000 SFE

In [130]: df.dtypes
Out[130]:
A float64
B float64
C float64
D object
dtype: object

更新 2:

In [143]: df[['A','B','C']] = df[['A','B','C']].apply(pd.to_numeric, errors='coerce')

In [144]: df
Out[144]:
A B C D
0 123.45 -9.0700 34.000 AAA
1 34.00 5.4000 34.980 AVF
2 -9.00 3.0000 -9.654 ERD
3 4.00 1.0000 45.000 DFE
4 5.00 4.5557 6.000 SFE

In [145]: df.dtypes
Out[145]:
A float64
B float64
C float64
D object
dtype: object

关于pandas - 将多个数据类型转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43987237/

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