类型错误“DataFrame”对象不可调用

我创建了一个函数并在 for 循环中使用它,但收到TypeError 'DataFrame' object is not callable


def 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')   

有人知道这个问题吗?


临摹微笑
浏览 199回答 1
1回答

慕尼黑5688855

不要将变量命名为与函数名称相同。您本质上是用 DataFrame 覆盖您的函数,因此当您的第二次迭代发生时,它Freq是一个 dataframe 而不是您认为的函数。freq_var = ['A', 'B', 'C', 'D', 'E']for col in freq_var:&nbsp; &nbsp; freq_df = Freq(data, 'KEYS', f'{col}')&nbsp; &nbsp; print(f'============ {col} frequency table ============\n{freq_df}\n\n')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python