Home > Enterprise >  How to deal with error creating pivot on empty dataframe?
How to deal with error creating pivot on empty dataframe?

Time:01-25

I have a dataframe, which I need to filter and than do s.th. with the results (pivot...).

Sometimes the result is an empty dataframe and the call to pivot fails. How can I deal with this.

The filtering is done like this:

df_sparen = df[(df['INCOME_EXPENSES'] == "Transaktion abbuchen") & (df['CATEGORY'] == "Trade Republic")]

than the pivot table call

table_sparen = df_sparen.pivot_table(values='AMOUNT', index=['INCOME_EXPENSES'],

                                     columns=['MONTHYEAR'], aggfunc=np.sum, margins=True)

This breaks as df_sparen is empty with the error:

ValueError: No objects to concatenate

Any advice how to deal with this is very much appriciated?

CodePudding user response:

You can use df.empty:

table_sparen = (
    df_sparen.pivot_table('AMOUNT', 'INCOME_EXPENSES', 'MONTHYEAR', 
                          aggfunc=np.sum, margins=True)
        if not df_sparen.empty else pd.DataFrame({'All': {'All': 0}})
)

CodePudding user response:

Just check if the dataframe isn't empty?

df_sparen = df[(df['INCOME_EXPENSES'] == "Transaktion abbuchen") & (df['CATEGORY'] == "Trade Republic")]

if len(df_sparen) > 0:
    table_sparen = df_sparen.pivot_table(values='AMOUNT', index=['INCOME_EXPENSES'], columns=['MONTHYEAR'], aggfunc=np.sum, margins=True)

or use a try/except clause:

try:
    df_sparen = df[(df['INCOME_EXPENSES'] == "Transaktion abbuchen") & (df['CATEGORY'] == "Trade Republic")]
    table_sparen = df_sparen.pivot_table(values='AMOUNT', index=['INCOME_EXPENSES'], columns=['MONTHYEAR'], aggfunc=np.sum, margins=True)

except ValueError:
    print(f'Empty DataFrame for {"Transaktion abbuchen"} and {"Trade Republic"}')
  •  Tags:  
  • Related