gpt4 book ai didi

Python Pandas 将字符串转换为 int/float

转载 作者:行者123 更新时间:2023-11-28 22:16:20 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,我正在尝试操作它,以便“数量”列从字符串(“hh.hh '小时'”)转换为 int 或 float。

我想知道在这种情况下最佳做法是什么。我试过 pd.to_numeric(),但没有成功。我认为我的问题在于每个字符串末尾的“小时数”。

是否有另一个函数可以识别数字字符并简单地忽略字符串的“小时”部分,或者我是否首先需要在使用内置 dtype 转换函数 (pd.to_numeric) 之前修剪最后 5 个字符?谢谢!

           day  amount
2018-08-23 3 24.00 hours
2018-08-24 4 8.00 hours
2018-08-25 5 32.00 hours
2018-08-26 6 24.00 hours
2018-08-27 0 24.00 hours

最佳答案

只需使用字符串方法只获取重要的数字。有很多选项可用,具体取决于您的列的困惑程度或格式:

import pandas as pd

df['amount'] = pd.to_numeric(df.amount.str.replace('hours', ''), downcast='integer')
# or
df['amount'] = pd.to_numeric(df.amount.str[:-5], downcast='integer')
# or
df['amount'] = pd.to_numeric(df.amount.str.extract('(\d+\.?\d*)')[0], downcast='integer')

所有输出:

            day  amount
2018-08-23 3 24
2018-08-24 4 8
2018-08-25 5 32
2018-08-26 6 24
2018-08-27 0 24

关于Python Pandas 将字符串转换为 int/float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260517/

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