使用@interact,在输入中使用字符串列表,将字符串列表拆分为字母列表。无论如何要阻止这个?

Using @interact, using a list of strings as in input, the list of strings is split into a list of letters. Is there anyway to stop this?

我正在使用 ipython 小部件,所以不确定为什么会出现此错误

使用@interact 和字符串列表作为以下函数的输入:

@wdg.interact(lines=["Number of cases", "Number of admissions", "Number of deaths"])
def time_series_graph( lines):
    n_lines=len(lines)
    if n_lines>0:
        data[list(lines)].plot()
    else:
        print("Select the data you want to print.")

我已经有一个 pandas 数据框,其列名与列表行中的一样,但此代码不起作用。字符串列表被拆分,因此每个字母都是列表的成员。

这是(除其他外)显示的错误:

KeyError: "None of [Index(['N', 'u', 'm', 'b', 'e', 'r', ' ', 'o', 'f', ' ', 'c', 'a', 's', 'e',\n 's'],\n dtype='object')] are in the [columns]"

这是什么原因,有什么解决办法吗?

感谢您的帮助!

因为您使用的是下拉菜单 select或者,只有一个字符串选项被传入,而不是字符串列表。

因此,

  1. lines在函数作用域中实际上是一个字符串。
  2. list(lines) 生成每个字符的列表
  3. 然后尝试 select 这些列失败。

试试改用 SelectMultiple?您可以按住 Shift 并单击 select 个以上。

import ipywidgets as wdg

@wdg.interact(lines=wdg.SelectMultiple(options=["Number of cases", "Number of admissions", "Number of deaths"]))
def time_series_graph(lines):
    print(lines)
    n_lines=len(lines)
    if n_lines>0:
        data[list(lines)].plot()
    else:
        print("Select the data you want to print.")