[英]KeyError inside a def function
I am transforming some data and I found myself in the situation where I needed to repeat the same process across different dataframes so I thought that building a function would be great.我正在转换一些数据,我发现自己需要在不同的数据帧上重复相同的过程,所以我认为构建一个 function 会很棒。
I started doing this:我开始这样做:
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
I got a KeyError: 'Search term' error
.我收到
KeyError: 'Search term' error
。
What I tried:我尝试了什么:
def()
structure def()
结构之外工作What is it that I overlooked/ misunderstood?我忽略/误解了什么?
Thank you for your time.感谢您的时间。
Use DataFrame.pipe
, because need pass DataFrame instead apply function for each column by .apply
:使用
DataFrame.pipe
,因为需要传递 DataFrame 而不是通过 .apply 为每一列应用.apply
:
fy21_word_counts = fy21.pipe(table_transformation, index, values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.