我有两个数据帧:

import numpy as np
import pandas as pd
import ipywidgets as widgets
import seaborn as sns

df = pd.DataFrame(np.random.rand(6,2), index=['Nr. 1', 'Nr. 2', 'Nr. 3', 'Nr. 4', 'Nr. 5', 'Nr. 6'], columns=['A', 'B', 'C', 'D'])

df2 = pd.DataFrame(np.array([[1, 2, 3, 4]]), columns=['a', 'b', 'c', 'd'])

我想做一个交互式绘图,在这里我可以通过下拉索引df来 Select 数据帧的行.

这是我的方法:

Index= df.index.tolist()
Nr = widgets.Dropdown(options=Nr, value=Nr[0], description='Number:', disabled=False)
button = widgets.Button(description='Plot', disabled = False, button_style='', tooltip = 'Plotting', icon='check')

out = widgets.Output(layout={'border': '1px solid black'})
box = widgets.VBox([Nr, button])
def on_button_clicked(b):
    with out:
         ax = sns.regplot(x=df_2[0], y=df.loc[[Nr]])
button.on_click(on_button_clicked, False)
display(box)

然而,我得到了这个错误:'None of [Index([Dropdown(description='Nr:', index = 4, options=('Nr. 1', 'Nr. 2', 'Nr. 3', 'Nr. 4'), value = 'Nr. 1')], dtype = 'object', name='Nr')] are in the [index]'

我错过了什么?

推荐答案

import ipywidgets as widgets
from ipywidgets import interact  
import pandas as pd
import numpy as np
import seaborn as sns

# create wide dataframe
df = pd.DataFrame(np.random.rand(6, 4),
                  index=['Nr. 1', 'Nr. 2', 'Nr. 3', 'Nr. 4', 'Nr. 5', 'Nr. 6'],
                  columns=['A', 'B', 'C', 'D'])

# convert the dataframe to long form
df = df.reset_index().melt(id_vars='index')

# convert the categorical value to a number with cat.codes or factorize
df['fac'], cats = df.variable.factorize() 
# df['fac'] = df.variable.astype('category').cat.codes
# cats = df.variable.unique()

# display(df.head())
   index variable     value  fac
0  Nr. 1        A  0.700304    0
1  Nr. 2        A  0.375954    0
2  Nr. 3        A  0.168559    0
3  Nr. 4        A  0.962506    0
4  Nr. 5        A  0.503662    0

交互式绘图

# get the unique values from the column used to select the data
idx = df['index'].unique()
@interact(Idx = idx)
def f(Idx):
    # select the relevant data
    data = df[df['index'].eq(Idx)]
    # plot
    ax = sns.regplot(data=data, x='fac', y='value')
    # set the x-ticks and labels
    ax.set_xticks(df.fac.unique(), cats)
    return ax

enter image description here

Python相关问答推荐

如何计算两极打印机中 * 所有列 * 的出现次数?

Pandas 有条件轮班操作

标题:如何在Python中使用嵌套饼图可视化分层数据?

Python,Fitting into a System of Equations

numpy卷积与有效

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

Pandas DataFrame中行之间的差异

在单个对象中解析多个Python数据帧

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

寻找Regex模式返回与我当前函数类似的结果

在pandas/python中计数嵌套类别

如何使用正则表达式修改toml文件中指定字段中的参数值

Python将一个列值分割成多个列,并保持其余列相同

合并相似列表

Seaborn散点图使用多个不同的标记而不是点

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

如何将一个文件的多列导入到Python中的同一数组中?

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

如何删除剪裁圆的对角线的外部部分

是否从Python调用SHGetKnownFolderPath?