我想在Jupyter Notebook上创建一个按钮,以替换以下代码中使用的if语句:
from ipywidgets import interact
import ipywidgets as widgets
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
import scipy as sci
# I create two dataset
x = np.linspace(0, 2*np.pi, 2000)
y1=np.sin(2*x)
y2=np.sin(4*x)
y3=np.sin(8*x)
f1=np.exp(-x**2)
f2=np.exp(-2*x**2)
f3=np.exp(-3*x**2)
ms=[y1,y2,y3]
mt=[f1,f2,f3]
ms=np.transpose(ms)
mt=np.transpose(mt)
dataset_1=pd.DataFrame(ms)
dataset_2=pd.DataFrame(mt)
control=1 # Selection parameter used in the if condition
# This is the condition that I want to replace by a button
if control==1:
data=dataset_1
data.plot()
plt.show()
elif control==0:
data=dataset_2
data.plot()
plt.show()
在这里,我创建了两个分别由三个正弦和高斯组成的数据集。 我想知道是否可以使用这样的单选按钮:
widgets.RadioButtons(
options=['dataset 1', 'dataset 2'],
description='Switching:',
disabled=False
)
答案 0 :(得分:0)
可能只需要根据条件创建一个简单的函数并使用交互即可。
from ipywidgets import interact
import ipywidgets as widgets
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
import scipy as sci
# I create two dataset
x = np.linspace(0, 2*np.pi, 2000)
y1=np.sin(2*x)
y2=np.sin(4*x)
y3=np.sin(8*x)
f1=np.exp(-x**2)
f2=np.exp(-2*x**2)
f3=np.exp(-3*x**2)
ms=[y1,y2,y3]
mt=[f1,f2,f3]
ms=np.transpose(ms)
mt=np.transpose(mt)
dataset_1=pd.DataFrame(ms)
dataset_2=pd.DataFrame(mt)
def f(Dataset):
control = Dataset
if control == 'dataset 1':
data=dataset_1
data.plot()
plt.show()
elif control== 'dataset 2':
data=dataset_2
data.plot()
plt.show()
return Dataset
interact(f, Dataset = widgets.RadioButtons(
options=['dataset 1', 'dataset 2'],
description='Switching:',
disabled=False))
答案 1 :(得分:0)