close

[Solved] Key error when selecting columns in pandas dataframe after read_csv

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Key error when selecting columns in pandas dataframe after read_csv in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Key error when selecting columns in pandas dataframe after read_csv Error Occurs?

Today I get the following error Key error when selecting columns in pandas dataframe after read_csv in python.

How To Solve Key error when selecting columns in pandas dataframe after read_csv Error ?

  1. How To Solve Key error when selecting columns in pandas dataframe after read_csv Error ?

    To Solve Key error when selecting columns in pandas dataframe after read_csv Error if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.

  2. Key error when selecting columns in pandas dataframe after read_csv

    To Solve Key error when selecting columns in pandas dataframe after read_csv Error if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.

Solution 1

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don’t have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

Solution 2

if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.

df[["product_id","customer_id","store_id"]]

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read