【问题标题】:How to convert an object that is a fraction to an integer in python如何在python中将分数对象转换为整数
【发布时间】:2023-02-10 04:49:58
【问题描述】:

ValueError:以 10 为底的 int() 的无效文字:'100/100'

我的数据集有一个评级列,其中包含以对象形式呈现的评级:98/100、99/100、60/100 等...

我需要将此列转换为 int,例如:98、99、60 等

我试过 .astype 和 int(float())

【问题讨论】:

  • 您有多相信您的文本是“安全的”?该值是否总是超出“100”?

标签: python


【解决方案1】:

您可以使用 apply 方法,然后使用 astype 将列转换为整数值:

df = df['rating'].apply(lambda x: x.split('/')[0]).astype(int))

import pandas as pd
df = pd.DataFrame.from_dict({'rating': ['90/100', '88/100', '35/100']})
df['rating'] = df['rating'].apply(lambda x: x.split('/')[0]).astype(int)
print(df)

退货:

   rating
0  90
1  88
2  35

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 2012-10-20
    • 2021-12-06
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2017-10-18
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多