KeyError: 'NOX'

Question:

Input:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
CO =[]
NO2 =[]
NOX =[]
SO2 =[]
FSP=[]
RSP=[]
O3=[]
no=0

f = open('Air Pollutants.csv') 
data = pd.read_csv(f,encoding='utf-8',header=None, sep = 't') 


NOX=data['NOX']
NO2=data['NO2'] 

sns.kdeplot(NOX,shade=True, color="orange") # to make a figure of NOX
sns.kdeplot(NO2,shade=True, color="blue") # to make a figure of NO2
plt.show()

Output:

File "/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3631, in get_loc
raise KeyError(key) from err

KeyError: ‘NOX’

Why there is a key error when I try to read the columns NOX and NO2? And how to solve this error, thanks.

csv. file as follows:

DATE,HOUR,STATION,CO,FSP,NO2,NOX,O3,RSP,SO2

1/1/2022,01,TUEN MUN,75,38,39,40,83,59,2

1/1/2022,02,TUEN MUN,72,35,29,30,90,61,2

1/1/2022,03,TUEN MUN,74,38,28,30,91,66,2

1/1/2022,04,TUEN MUN,76,39,31,32,79,61,2

Asked By: Jesse Ko

||

Answers:

Ok, I’m not sure what you’re doing wrong but I took the file that I downloaded from the location you provided and simply did this:

import pandas as pd

data = pd.read_csv('/home/pav/Downloads/air_hourly.csv', skiprows=11)

That’s it. It gives me a properly formatted dataframe:

data.columns
# Out: Index(['DATE', 'HOUR', 'STATION', 'CO', 'FSP', 'NO2', 'NOX', 'O3', 'RSP'], dtype='object')

And

NOX = data.loc[:, 'NOX']
NOX.shape
# Out: (4344,)
Answered By: pavel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.