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