Pandas KeyError
Выводит ошибку KeyError?!
# Функции подготовки данных
df = pd.read_csv('data.csv', sep=',')
print(df)
print(df.dtypes)
# Напишем несколько функций преобразования
temper_convertor = lambda x: x.replace('°C', '').strip()
pressure_convertor = lambda x: x.replace('Па', '').strip()
prec_convertor = lambda x: True if x == 'Да' else False
# Применим созданные функции к элементам структуры
df['Температура'] = df['Температура'].apply(temper_convertor).astype('float64')
df['Давление'] = df['Давление'].apply(pressure_convertor).astype('int64')
df['Осадки'] = df['Осадки'].apply(prec_convertor)
print(df.dtypes)
csv file
Температура, Давление, Осадки, Дата
-8 °C, 96292 Па, Да, 2019-11-20
-10.3 °C, 97292 Па, Да, 2019-11-21
-9.1 °C, 96325 Па, Нет, 2019-11-22
error
Traceback (most recent call last):
File "/Users/theblackmonkey/PycharmProjects/MyLearn/venv/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3802, in get_loc
return self._engine.get_loc(casted_key)
File "index.pyx", line 153, in pandas._libs.index.IndexEngine.get_loc
File "index.pyx", line 182, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Давление'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/theblackmonkey/PycharmProjects/MyLearn/PANDAS - Working with data/Chapter 3. Data Types in pandas/3.2 Инструменты для работы с типами.py", line 15, in <module>
df['Давление'] = df['Давление'].apply(pressure_convertor).astype('int64')
File "/Users/theblackmonkey/PycharmProjects/MyLearn/venv/lib/python3.9/site-packages/pandas/core/frame.py", line 4090, in __getitem__
indexer = self.columns.get_loc(key)
File "/Users/theblackmonkey/PycharmProjects/MyLearn/venv/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3809, in get_loc
raise KeyError(key) from err
KeyError: 'Давление'
Ответы (1 шт):
Автор решения: Алексей Р
→ Ссылка
Колонки 'Давление' нет во фрейме, так же как и 'Осадки' и 'Дата'. В этом можно убедиться, распечатав названия колонок print(df.columns) и получив
Index(['Температура', ' Давление', ' Осадки', ' Дата'], dtype='object')
Дело в ведущих пробелах в первой строке csv Температура, Давление, Осадки, Дата.
Можно сделать так, добавив ведущий пробел:
df[' Давление'] = df[' Давление'].apply(pressure_convertor).astype('int64')
df[' Осадки'] = df[' Осадки'].apply(prec_convertor)
А можно почистить названия столбцов во фрейме:
df.columns = df.columns.str.strip()
и далее использовать ваш код без изменений.
Но лучше сразу прочесть csv с заголовками без ведущих пробелов, используя аргумент skipinitialspace=True:
df = pd.read_csv(r'c:\test\data.csv', skipinitialspace = True, sep=',')
Есть еще способ - задать regex разделитель вида:
df = pd.read_csv(r'c:\test\data.csv', sep=',\s*', engine='python')
который также удалит лишние пробелы.