我創(chuàng)建了一個(gè)函數(shù)并在 for 循環(huán)中使用它,但收到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如果我不調(diào)用Freq()直接輸入就可以了,沒有錯(cuò)誤,輸出成功。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') 有人知道這個(gè)問題嗎?
1 回答

慕尼黑5688855
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
不要將變量命名為與函數(shù)名稱相同。您本質(zhì)上是用 DataFrame 覆蓋您的函數(shù),因此當(dāng)您的第二次迭代發(fā)生時(shí),它Freq是一個(gè) dataframe 而不是您認(rèn)為的函數(shù)。
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')
添加回答
舉報(bào)
0/150
提交
取消