简体   繁体   中英

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

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 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?

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

x = dataset(columns=features)

or

x = dataset[features]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM