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

ltskdhd1  于 2023-05-15  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个长列名的dataframe,想使用GUI来选择感兴趣的列,而不是键入名称,其中一些可能有空格等,所以不是标签完成友好。在vscode中有没有使用notebook的示例代码?

fcg9iug3

fcg9iug31#

经过一些尝试和错误之后,这段代码通过子类化完成了这项工作,这样您就可以使用额外的自定义实用程序函数来增强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()

相关问题