如何为熊猫数据框创建交互式列选择面板

问题描述 投票:0回答:1

我有一个列名很长的数据框,我想使用 GUI 来选择感兴趣的列,而不是键入名称,其中一些名称可能有空格等,因此不利于制表符完成。在使用笔记本的 vscode 中是否有任何示例代码可以做到这一点?

python pandas dataframe user-interface interactive
1个回答
-1
投票

经过反复试验,这段代码通过子类化来完成工作,这样你就可以用额外的自定义实用函数来增强 pd.DataFrame

# create a subclass


import panel as pn

class myDataFrame (pd.DataFrame):
    """A class that creates a Panel panel that allows the user to select columns from a dataframe.

    Args:
        df: The dataframe to select columns from.

    Attributes:
        selected_df: The selected dataframe.
    """
    
    def __init__(self, df):
        import warnings
        super().__init__(df)
        # Disable the warning temporarily
       # Disable the warning
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            
            self.df=df
            self.selected_df = None
            self.selected_columns = None
            self.column_checkboxes = [pn.widgets.Checkbox(name=column) for column in self.df.columns]

    def select_columns(self):
        """Selects the columns from the dataframe based on checkboxes' state.
        """

        # Get the selected columns from the checkbox widgets.
        selected_columns = [checkbox.name for checkbox in self.column_checkboxes if checkbox.value]

        # Create a new dataframe with the selected columns.
        self.selected_df = self.df[selected_columns]
        self.selected_columns = selected_columns

    def create_column_selection_panel(self):
        """Creates a Panel panel that allows the user to select columns from a dataframe.

        Returns:
        A Panel panel that allows the user to select columns from a dataframe.
        """

        # Create a row layout for the checkbox widgets.
        column_selection_row = pn.layout.Column(*self.column_checkboxes)

        # Create a button that will select the selected columns.
        
        select_columns_button = pn.widgets.Button(
            name="Select Columns",
            
            width=200,
            height=25,
        )

        # Connect the select columns button to the select columns function.
        select_columns_button.on_click(lambda event: self.select_columns())

        # Create a layout for the column selection panel.
        column_selection_panel = pn.layout.Column(
            column_selection_row,
            select_columns_button,
        )

        return column_selection_panel

    def get_selected_df(self):
        """Gets the selected dataframe.

        Returns:
        The selected dataframe.
        """

        return self.selected_df
# example usage -works in vscode jupyter notebook
newdf=myDataFrame(df)
newdf.create_column_selection_panel()
newdf.selected_columns
newdf.get_selected_df()
© www.soinside.com 2019 - 2024. All rights reserved.