函数内触发KeyError: 'Search term',求问题排查与解决
问题分析与解决
核心错误原因
你误用了pandas.DataFrame.apply()方法:
apply默认会对DataFrame的每一列(axis=0)或每一行(axis=1)单独传入函数,而非把整个DataFrame作为参数传给table_transformation。- 函数实际接收到的
dataframe参数是单个Series(某一列),而非完整的DataFrame,自然找不到'Search term'列,触发KeyError。
修复步骤
替换
apply为直接调用函数
将:fy21_word_counts = fy21.apply(table_transformation, args=(index, values))修改为:
fy21_word_counts = table_transformation(fy21, index, values)修正函数内的无状态操作
sort_values和drop方法会返回新的DataFrame,不会修改原对象,需要赋值回去才会生效:def table_transformation(dataframe, index, values): dataframe_to_pivot = pd.pivot_table(data= dataframe, index= index, values= values, aggfunc= {values[0]: count_words, values[1]: np.sum, values[2]: np.sum} ) # 赋值保留排序结果 dataframe_to_pivot = dataframe_to_pivot.sort_values(by=[index], ascending= True) sum_counts = dataframe_to_pivot.iloc[9:].sum() # 赋值保留删除后的结果 dataframe_to_pivot = dataframe_to_pivot.drop(dataframe_to_pivot.index[9:].tolist()) dataframe_to_pivot.loc['+10'] = sum_counts return dataframe_to_pivot
逻辑验证说明
你提到函数内逻辑在外部能正常运行,是因为外部直接传入了完整的DataFrame,而apply传入的是单个列,这就是两者的本质区别。
内容的提问来源于stack exchange,提问作者Osaka
相关产品推荐
相关产品推荐

