Skip to content
Advertisement

Trying to pass user input in usecols Pandas

I’m trying to ask the user which columns do they want read in the dataframe from a csv file. I’ve been trying the following:

    col = [0, 1]

    df = pd.read_csv(filename, usecols = lambda x: x in col, index_col=False, header=1)

But even this gives an error. Any suggestions? I think so I’m not able to understand the lambda function. The error I’m getting is: pandas.errors.EmptyDataError: No columns to parse from file

Advertisement

Answer

You can pass the col list as the answer to the usecols parameter.

col_list = [0, 1]
df = pd.read_csv(filename, usecols = col_list, index_col=False, header=1)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement