python怎么定义浮点数_我如何在Python中定义一个函数来将对象列转换为浮点数?...

只是为了

object

数据类型,可以使用

select_dtypes

df[df.select_dtypes('object').columns] = df.select_dtypes('object').astype(float)

例如:

>>> df

col1 col2 col3 col4

0 1 0.452893 2 8

1 2 0.745232 3 6

2 1 0.374296 3 1

3 3 0.398660 3 4

4 2 0.902737 2 1

5 3 0.940392 3 0

6 3 0.382493 3 0

7 2 0.684829 3 4

8 2 0.506248 3 8

9 1 0.161701 3 3

>>> df.dtypes

col1 object

col2 float64

col3 object

col4 int64

dtype: object

>>> df[df.select_dtypes('object').columns] = df.select_dtypes('object').astype(float)

>>> df.dtypes

col1 float64

col2 float64

col3 float64

col4 int64

dtype: object

:如果某些列的某些值无法转换为浮点值,则上面的方法将不起作用。你可以遍历它们,使用

pd.to_numeric

具有

errors='coerce'

downcast='float'

:

>>> df

col1 col2 col3 col4

0 3 0.594651 2 6

1 3 0.677595 3 3

2 3 0.546434 1 0

3 3 0.454769 2 6

4 x 0.321130 2 3

5 2 0.473391 2 7

6 1 0.207182 2 7

7 2 0.883071 3 1

8 x 0.994372 2 4

9 1 0.052539 3 2

>>> df.dtypes

col1 object

col2 float64

col3 object

col4 int64

dtype: object

for col in df.select_dtypes('object').columns:

df[col] = pd.to_numeric(df[col], errors='coerce', downcast='float')

>>> df

col1 col2 col3 col4

0 3.0 0.594651 2.0 6

1 3.0 0.677595 3.0 3

2 3.0 0.546434 1.0 0

3 3.0 0.454769 2.0 6

4 NaN 0.321130 2.0 3

5 2.0 0.473391 2.0 7

6 1.0 0.207182 2.0 7

7 2.0 0.883071 3.0 1

8 NaN 0.994372 2.0 4

9 1.0 0.052539 3.0 2

>>> df.dtypes

col1 float32

col2 float64

col3 float32

col4 int64

dtype: object

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值