How to set a variable to read multiple columns from an excel file using pandas in python

Viewed 21

I have been trying to set a variable to read multiple columns from an excel file using pandas but it keeps giving me errors, what am I doing wrong?

I have tried this:

import pandas

dataset = pandas.read_excel('dataset.xlsx')

features = ["B", "D", "E"]

x = dataset(columns=[features])

But this gave me an error saying:

 line 7, in <module>
    x = dataset(columns=[features])
TypeError: 'DataFrame' object is not callable

I also tried this:

import pandas

dataset = pandas.read_excel('dataset.xlsx')

features = ["B", "D", "E"]

x = dataset[[features]]

Which gave this error " raise:

 KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: None of [Index([('B', 'D', 'E')], dtype='object')] are in the [columns]

What am I doing wrong? How can I fix this?

1 Answers

You pass a list of lists (with length 1) instead of a list. Remove the additional [] around features:

x = dataset[features]
Related