【问题标题】:Why error appear when I apply function to dataframe?为什么将函数应用于数据框时会出现错误?
【发布时间】:2020-12-15 04:07:12
【问题描述】:
def function(s):
    if (s['col1'] == 'something1')|(s['col1'] == 'smth2')|(s['col1'] == 'smth3'):
        return 'A'
    elif (s['col1'] == 'smth4')|(s['col1'] == 'smth5'):
        return 'B'
    elif (s['col1'] == 'smth6')|(s['col1'] == 'smth7'):
        return 'C'
    else:
        return 'D'

上面的功能有效。但是当我将它应用到数据框时:

df['new_col'] = df.apply(function, axis = 1)

我明白了:

TypeError: ("'bool' object is not callable", 'occurred at index 0') 

【问题讨论】:

  • 您确定没有另一个名为function 的变量覆盖了实际的函数定义吗?
  • 对我来说工作正常。
  • 不,没有一个叫做函数的变量。

标签: python pandas function dataframe typeerror


【解决方案1】:

对我来说工作正常,这里是 Series.isinnumpy.select 的替代解决方案:

df = pd.DataFrame({
    'col1':['something1','jeff bridges','smth7','billy boy','smth5']})


print (df)

def function(s):
    if (s['col1'] == 'something1')|(s['col1'] == 'smth2')|(s['col1'] == 'smth3'):
        return 'A'
    elif (s['col1'] == 'smth4')|(s['col1'] == 'smth5'):
        return 'B'
    elif (s['col1'] == 'smth6')|(s['col1'] == 'smth7'):
        return 'C'
    else:
        return 'D'
    
df['new_col'] = df.apply(function, axis = 1)

m1 = df['col1'].isin(['something1','smth2','smth3'])
m2 = df['col1'].isin(['smth4','smth5'])
m3 = df['col1'].isin(['smth6','smth7'])

df['new_col1'] = np.select([m1, m2, m3], ['A','B','C'], default='D')
print (df)
           col1 new_col new_col1
0    something1       A        A
1  jeff bridges       D        D
2         smth7       C        C
3     billy boy       D        D
4         smth5       B        B

【讨论】:

  • 非常感谢,第二个有效,但我不明白为什么另一个无效?
  • @SaidTaxmezov - 困难的问题,对我来说工作正常。如果更改函数名称没有帮助?
猜你喜欢
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 2022-08-03
  • 2021-08-27
  • 2011-05-18
  • 1970-01-01
相关资源
最近更新 更多