我正在寻找一种解决方案,从一个数据帧中动态 Select 两列(例如使用ipywidgets或steamlit),并使用该 Select 创建一个新的数据帧.

其目的是允许用户从较大的数据集中 Select 两列,以允许过滤这两列,从而删除用于回归和绘图的NAN.我不想键入每个列标题,因为每次使用数据帧都会更改.任何帮助都会大有帮助!

import ipywidgets as widgets
import pandas as pd

df = pd.DataFrame({'A' : [4,NaN], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})

x_choice = widgets.Dropdown(
    options=list(df.select_dtypes('number').columns)[0:],
    description='Number:',
    disabled=False,
)

y_choice = widgets.Dropdown(
    options=list(df.select_dtypes('number').columns)[1:],
    description='Number:',
    disabled=False,
)


dfX = pd.DataFrame(x_choice, y_choice)
dfX.dropna()

推荐答案

这一次使用的是流线型照明方法.框架的样式是为了在使用st.dataframe()显示时看起来更好,但您可以忽略它.

密码

"""
Creates a new datafame based on selected column from existing dataframe.
"""

import pandas as pd
import streamlit as st 


df = pd.DataFrame({'A' : [4,None], 'B' : [10,20],
                   'C' : [100,50], 'D' : [-30,-50],
                   'E' : [1500,800], 'F' : [0.258,1.366]})

# Apply styler so that the A column will be displayed with integer value because there is None in it.
df_style = df.style.format(precision=2, na_rep='MISSING', thousands=",", formatter={('A'): "{:.0f}"})

st.write('Current dataframe')
st.dataframe(df_style)

# We use a form to wait for the user to finish selecting columns.
# The user would press the submit button when done.
# This is done to optimize the streamlit application performance.
# As we know streamlit will re-run the code from top to bottom
# whenever the user changes the column selections.
with st.form('form'):
    sel_column = st.multiselect('Select column', df.columns,
       help='Select a column to form a new dataframe. Press submit when done.')
    drop_na = st.checkbox('Drop rows with missing value', value=True)
    submitted = st.form_submit_button("Submit")
    
if submitted:
    dfnew = df[sel_column]
    if drop_na:
        dfnew = dfnew.dropna()

    st.write('New dataframe')
    dfnew_style = dfnew.style.format(precision=2, na_rep='MISSING', thousands=",", formatter={('A'): "{:.0f}"})
    st.dataframe(dfnew_style)

输出

enter image description here

Python相关问答推荐

比较2 PD.数组的令人惊讶的结果

将输入管道传输到正在运行的Python脚本中

如何列举Pandigital Prime Set

无法使用requests或Selenium抓取一个href链接

运输问题分支定界法&

形状弃用警告与组合多边形和多边形如何解决

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

如何在Python中找到线性依赖mod 2

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

如何在Python中获取`Genericums`超级类型?

Geopandas未返回正确的缓冲区(单位:米)

OpenCV轮廓.很难找到给定图像的所需轮廓

如何在Gekko中使用分层条件约束

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

获取git修订版中每个文件的最后修改时间的最有效方法是什么?

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

Pandas:计数器的滚动和,复位

如何获取给定列中包含特定值的行号?

来自任务调度程序的作为系统的Python文件

以元组为索引的Numpy多维索引