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

时间:2017-05-15 19:18:51

标签: pandas

使用pandas,如何转换数据类型的多个dateframe列" object"漂浮。

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'对象没有属性' apply':

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

1 个答案:

答案 0 :(得分:2)

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

<强> UPDATE2:

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