user17856557
user17856557

Reputation: 47

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?

Upvotes: 0

Views: 83

Answers (2)

scr
scr

Reputation: 962

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

Upvotes: 2

Jakemoyo
Jakemoyo

Reputation: 181

You can use * in front of variables to unpack them.

Try: df[['d', 'y', *options]] and see if that works.

Upvotes: 2

Related Questions