Home > Net >  Define a function everytime I need to use it python
Define a function everytime I need to use it python

Time:09-24

I am trying to use this function in a for loop but everytime the function runs for 2nd time it does not work and throw this error. I realised that everytime I need to use it I need to execute the cell that define it. Is it possible that I can define it only once and run it multiple times inside a for loop as I normally do?

Thanks and best wishes

def table_for_something(df_1):

    #rodeo_table.pivot_table(values=['Quantity'],index = ['Process'],aggfunc=['sum'])
    #try:
    #df_1= df_1.copy()
    df_1['Area'] = df_1['ID'].str[:5]
    df_1= df_1.loc[df_1['ID2']>0]
    df_1= df_1.pivot_table(values='Quantity',index = ['Area'],aggfunc='sum').sort_values(by='Quantity').reset_index()
    df_1= df_1.rename(columns = {'Quantity':'Units'})
    df_1['% Units'] = round(df_1['Units'] / df_1['Units'].sum() * 100,1)
    df_1.sort_values(by='Units',ascending = False)


    list_a = []
    total = df_1['Units'].sum()

    list_a.append("Grand Total")
    list_a.append(total)
    list_a.append('100%')

    df_1.at["15"] = list_a 


    df_1['% Units'] = df_1['% Units'].apply(lambda x : str(x)   '%')


        #df_1
    #except KeyError:
     #   print('something')


    return df_1

The error that I get is the following, but I only get it when I execute the function for second time without declaring it


TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_17788/1667321701.py in ----> 1 table_whatever = table_for_something(table)

TypeError: 'DataFrame' object is not callable

The code has been slightly modified for confidencial terms

CodePudding user response:

I'd need to see the section where you're making the function call in the loop, but based on the error, it seems like you might have reused the name of the function at some point, so that the second time it tries to call the function, that name actually references a DataFrame object.

CodePudding user response:

I run in my pc and it is run clear but for a once. Where is your loop here?

  • Related