【问题标题】:Turn a function into a class in Pandas在 Pandas 中将函数转换为类
【发布时间】:2020-12-10 18:39:40
【问题描述】:

我的数据框中有以下列:

我在数据框中添加了一个新列,以便显示获胜者的姓名:

如果团队 1 的目标 > 团队 2 的目标,那么获胜者就是团队 1 的名称。

我使用了以下函数,它按预期工作:

def winner(row):
    if row['Team 1 goals'] > row['Team 2 goals']:
        return row['Team 1 name']
    elif row['Team 2 goals'] > row['Team 1 goals']:
        return row['Team 2 name']
    else:
        return 'Draw'

df['Winner of The Game'] = df.apply(winner, axis=1)

但是,我需要将这段代码用作一个类。

我使用这样的类:

class winner:
    def __init__(self,row):
        self.row=row
        def winner(row):
            if self.row['Team 1 goals'] > self.row['Team 2 goals']:
                return  obj['Team 1 name']
            elif self.row['Team 2 goals'] > self.row['Team 1 goals']:
                return self.row['Team 2 name']
            else:
                return 'Draw'

此时,我的表格中的最终输出将是这样的(它不会显示获胜队伍的正确名称):

我应该如何修复我的课程,以便它显示正确的获胜团队的名称?

【问题讨论】:

  • 您应用的是类而不是其中的方法。使用df.apply(winner.winner) 你的缩进也不希望在你的代码中是正确的。
  • 这样吗? wc['Winner of The Game'] = wc.apply(winner.winner, axis=1) 然后我得到这个错误: AttributeError: type object 'winner' has no attribute 'winner'
  • 你有错误的缩进 - 你有 def winnerdef __init__ 里面 - 所以它找不到 winner.winnerdef winner 应该有相同的缩进 def __init__

标签: python pandas class


【解决方案1】:
  1. 您的缩进已关闭。
  2. 您正在调用类对象

这是您的代码块的更简单版本

class winner:
    def __init__(self,row):
        self.row=row
    def winner(row):
        return 'Draw'
df = pd.DataFrame([[1],[2],[3]],columns=['a'])

df['new']= df.apply(winner.winner,axis=1)
df

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2023-03-07
    • 2014-05-19
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多