【问题标题】:How to access single columns in pandas for loop?如何访问熊猫 for 循环中的单列?
【发布时间】:2022-11-04 14:57:36
【问题描述】:

我有一列的评级像“4.1/5”我想删除斜杠(/),它是一个对象类型。我想将它转换为浮点数,所以我试图创建一个函数来做到这一点。

请纠正我做错了什么。我正在尝试类似的东西

def remove_slash_from_rating(ratings):
    for i in ratings:
        df[rate] = df[rate].str.replace(r'/','')

但是当我估算它时 (df["rate"] = df["rate"].apply(remove_slash_from_rating)) 然后我得到一个错误

NameError: name 'rate' is not defined

请检查上面的帖子

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要在循环中使用i 来遍历列

    检查下面的代码

    def remove_slash_from_rating(ratings):
        for i in ratings:
            df[i] = df[i].str.replace(r'/','')
    

    【讨论】:

      【解决方案2】:

      IIUC 用途:

      df["rate"] = df["rate"].str.replace(r'/','')
      

      【讨论】:

        猜你喜欢
        • 2013-10-03
        • 2022-07-18
        • 1970-01-01
        • 2019-05-11
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 2022-01-08
        • 1970-01-01
        相关资源
        最近更新 更多