如何将索引传递给函数?将其分配给列时,似乎工作正常,但将其传递给外部函数时,效果不佳:
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
我不太了解您要做什么。但是您的代码中有两件事:
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。也许要详细说明您的操作,以便我们可以帮助您重写函数。