【问题标题】:Pandas - convert value as type string to floatPandas - 将值作为字符串类型转换为浮点数
【发布时间】:2021-02-07 16:24:47
【问题描述】:

在我的 df 中,我将一些值设置为 dtype(str)

      x
  27:47
  13:45
  10:45

我想将它们转换为float,最后是:

      x
  27.47
  13.45
  10.45

我该怎么做?

【问题讨论】:

  • 27 mins, 47 seconds 不是27.47 分钟?
  • 可以是'.',没问题
  • 我的意思是 1 分钟 = 60 秒,所以 47 seconds 大约是 .76 分钟,而不是 .47 分钟。
  • 名字无所谓,真的,只是转换

标签: python pandas string datetime


【解决方案1】:

在你的情况下,你可以这样做:

df['x'] = df['x'].str.replace(':','.').astype(float)

输出:

       x
0  27.47
1  13.45
2  10.45

【讨论】:

    【解决方案2】:

    试试这个:

    df['x'] = df['x'].replace(to_replace=":",value=".").astype(float)
    

    【讨论】:

    • .str 是必需的。
    • 不。因为这是 Pandas .replace() 方法
    • 好吧,下面的解决方案奏效了,唯一的区别是那个....
    • 是的...我确保通过df.x.astype(str)...但不知何故它只适用于替换之前的.str
    • 对于之前的我来说,没有.str,它仍然可以工作,仍然无法弄清楚是什么原因
    猜你喜欢
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多