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

Time:04-14

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?

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

Just use *list to break (unpack) the structure of list as below

Some useful references : Unpack list to variables

import pandas as pd


df = pd.dataframe({
    'a': [1,2],
    'b': [3,4],
    'c': [5,6]
})

some_cols = ['b', 'c']
print(df['a', *some_cols])
  • Related