我创建了一个函数并在 for 循环中使用它,但收到TypeError 'DataFrame' object is not callabledef Freq(df, keyvar, *args): Freq = pd.DataFrame({'Frequency': df.groupby([*args])[keyvar].count()}).reset_index() Freq['Percent'] = (Freq['Frequency']/sum(Freq['Frequency'])*100).round(2) Freq['Cumulative Frequency'] = Freq['Frequency'].cumsum() Freq['Cumulative Percent'] = (Freq['Cumulative Frequency']/sum(Freq['Frequency'])*100).round(2) return Freq我用它Freq()来:freq_var = ['A', 'B', 'C', 'D', 'E']for col in freq_var: Freq = Freq(data, 'KEYS', f'{col}') print(f'============ {col} frequency table ============\n{Freq}\n\n')---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-30-2d4041b2961b> in <module>() 1 freq_var = ['A', 'B', 'C', 'D', 'E'] 2 for col in freq_var:----> 3 Freq = Freq(data, 'KEYS', f'{col}') 4 print(f'============ {col} frequency table ============\n{Freq}\n\n')TypeError: 'DataFrame' object is not callable如果我不调用Freq()直接输入就可以了,没有错误,输出成功。for col in freq_var: Freq = pd.DataFrame({'Frequency': data.groupby([col])['KEYS'].count()}).reset_index() Freq['Percent'] = (Freq['Frequency']/sum(Freq['Frequency'])*100).round(2) Freq['Cumulative Frequency'] = Freq['Frequency'].cumsum() Freq['Cumulative Percent'] = (Freq['Cumulative Frequency']/sum(Freq['Frequency'])*100).round(2) print(f'============ {col} frequency table ============\n{Freq}\n\n') 有人知道这个问题吗?
1 回答
慕尼黑5688855
TA贡献1848条经验 获得超2个赞
不要将变量命名为与函数名称相同。您本质上是用 DataFrame 覆盖您的函数,因此当您的第二次迭代发生时,它Freq是一个 dataframe 而不是您认为的函数。
freq_var = ['A', 'B', 'C', 'D', 'E']
for col in freq_var:
freq_df = Freq(data, 'KEYS', f'{col}')
print(f'============ {col} frequency table ============\n{freq_df}\n\n')
添加回答
举报
0/150
提交
取消