繁体   English   中英

def function 中的 KeyError

[英]KeyError inside a def function

我正在转换一些数据,我发现自己需要在不同的数据帧上重复相同的过程,所以我认为构建一个 function 会很棒。

我开始这样做:


count_words = lambda x: len(x)
index = 'word_count'
values= ['Search term', 'Clicks', 'Impr.']

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.sort_values(by=[index], ascending= True)
    sum_counts = dataframe_to_pivot.iloc[9:].sum()
    dataframe_to_pivot.drop(dataframe_to_pivot.index[9:].tolist())
    dataframe_to_pivot.loc['+10'] = sum_counts
    return dataframe_to_pivot

fy21_word_counts = fy21.apply(table_transformation, args=(index, values))
fy21_word_counts

我收到KeyError: 'Search term' error

我尝试了什么:

  • 我尝试在 function 中插入列的实际名称,但得到了同样的错误
  • function 内部的逻辑在函数的def()结构之外工作

我忽略/误解了什么?

感谢您的时间。

使用DataFrame.pipe ,因为需要传递 DataFrame 而不是通过 .apply 为每一列应用.apply

fy21_word_counts = fy21.pipe(table_transformation, index, values)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM