Search code examples
pythonpandaslistdataframedrop

How to get only some columns from dataframe based on list items?


I have a list named options=['pm1','pm10'] and a dataframe which contains more columns. I would like to get from the dataframe only the ds, y, pm1 and pm10 options, based on the options list. The wanted result:

df=df[['ds', 'y', 'pm1', 'pm10']]

But how could I achieve the same result by using the pm1 and pm10 taken from the list? I tried:

df=df[['ds', 'y',options]]

But this triggers the error:

TypeError: unhashable type: 'list'

How to solve this issue?


Solution

  • Try the following code:

    df=df[['ds', 'y',*options]]
    

    If you'd like to know why that works. It's because in this setting * isn't a multiplication, but the iterable unpacking operator