I get an error when trying to access a single or multiple elements in a pandas dataframe this way data["temp"]. Here is a code snippet on how I am loading the data:
import pandas
data = pandas.read_csv("weather_data.csv")
y = data["temp"]
print(y)
The csv file -> :
day;temp;condition Monday;12;Sunny Tuesday ;14;Rain Wednesday;15;Rain Tuesday ;14;Cloudy Friday;21;Sunny Saturday;22;Sunny Sunday;24;Sunny
Here is the error I am getting:
line 3790, in get_loc
return self._engine.get_loc(casted_key)
File "index.pyx", line 152, in pandas._libs.index.IndexEngine.get_loc
File "index.pyx", line 181, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'temp'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:NAME", line 5, in <module>
y = data["temp"]
File "C:\Users\sehab\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\frame.py", line 3893, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\sehab\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\indexes\base.py", line 3797, in get_loc
raise KeyError(key) from err
KeyError: 'temp'
is the problem with my code or with the package of pandas ?
You are not parsing your csv correctly since the default separator is ","
but you have ";"
instead.
Try the following:
data = pandas.read_csv(
filepath_or_buffer="weather_data.csv",
sep=";",
header=0
)