Search code examples
pythonpandastkintertreeview

The truth value of a dataframe is ambiguous only when running it through Tkinter


I have a function that is supposed to calculate the Mean and Median of some values in a pandas dataframe and then display them via Tkinter Treeview. I've tested the function without Tkinter and it works perfectly, but if I run it with it, it gives this error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

This my code:

def zip_mean_median():
    global clean_df
    clean_df['ACTIVITY DATE'] = pd.to_datetime(clean_df['ACTIVITY DATE']).dt.normalize()
    clean_df = clean_df.sort_values(by=['ACTIVITY DATE'])
    clean_df = clean_df.groupby([clean_df['ACTIVITY DATE'].dt.year, 'FACILITY ZIP'])['SCORE'].agg(['mean', 'median'])
    clean_df = ttk.Treeview(clean_df)
    clean_df.pack()

Solution

  • You cannot pass a dataframe directly to ttk.Treeview, you need to manually construct it. That can be done with the following function

    import tkinter as tk
    from tkinter import ttk
    
    def dataframe_to_treeview(root, dataframe):
        tree = ttk.Treeview(root, show='headings')
        columns = list(dataframe.columns)
    
        tree["columns"] = columns
        tree.pack(expand=tk.TRUE, fill=tk.BOTH)
    
        for i in columns:
            tree.column(i, anchor=tk.W)
            tree.heading(i, text=i, anchor=tk.W)
    
        for i, row in dataframe.iterrows():
            tree.insert("", "end", values=list(row))
    
        return tree
    

    As an example, you can use this function as follows:

    import pandas as pd
    
    inp = [{'Currency': 'EUR', 'Volume': '100', 'Country': 'SE'},
           {'Currency': 'GBP', 'Volume': '200', 'Country': 'SE'},
           {'Currency': 'CAD', 'Volume': '300', 'Country': 'SE'},
           {'Currency': 'EUR', 'Volume': '400', 'Country': 'SE'},
           {'Currency': 'EUR', 'Volume': '100', 'Country': 'DK'},
           {'Currency': 'GBP', 'Volume': '200', 'Country': 'DK'},
           {'Currency': 'CAD', 'Volume': '300', 'Country': 'DK'},
           {'Currency': 'EUR', 'Volume': '400', 'Country': 'DK'},
           ]
    df = pd.DataFrame(inp)
    root = tk.Tk()
    tree = dataframe_to_treeview(root, df)
    root.mainloop()