将数据帧的索引传递给函数

问题描述 投票:0回答:1

如何将索引传递给函数?将其分配给列时,似乎工作正常,但将其传递给外部函数时,效果不佳:

data=[{
    'directors': 'Ertil Altanaj',
    'director_score': 0.4,
}, {
    'directors': 'Erbil Altanaj',
    'director_score': 1,
}, {
    'directors': 'Richard Klemann',
    'director_score': 1,
}]
df=pd.DataFrame(data)
df['director_score_match'] = df.director_score >= 0.90


def other_is_true(row): # also, any way to convert this into a lambda?
    index=row.index
    field='director_score_match'
    l = df[field].tolist()
    del l[index]
    return any(l)

df['director_score_other_match'] = df.apply(other_is_true)


>>> TypeError: list indices must be integers or slices, not RangeIndex
python pandas
1个回答
2
投票

我不太了解您要做什么。但是您的代码中有两件事:

  • 如果要逐行应用,请使用axis=1
  • 行没有索引,但是有名称

更正:

def other_is_true(row):
    index=row.name # here
    field='director_score_match'
    l = df[field].tolist()
    del l[index]
    return any(l)

df['director_score_other_match'] = df.apply(other_is_true, axis=1) # and here

由于other_is_true是多语句函数,因此无法将其转换为lambda。也许要详细说明您的操作,以便我们可以帮助您重写函数。

© www.soinside.com 2019 - 2024. All rights reserved.