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?

Viewed 147

I'm am using ipython widgets so unsure why this error is occurring

Using @interact and a list of strings as an input to the function below:

@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.")

I already have a pandas data frame with the column names as in the list lines but this code does not work. The list of strings is split up so that each letter is a member of the list.

This (among others) is the error shown:

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]"

What is the reason for this and any idea how to fix it?

Thanks for your help!

1 Answers

Because you are using a dropdown selector, only one of your string choices is getting passed in, rather than a list of strings.

Hence,

  1. lines in the function scope is actually a string.
  2. list(lines) produces a list of each character
  3. Then trying to select those columns fails.

Try using a SelectMultiple instead? You can shift-click to select more than one.

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.")
Related