Я работаю с Pandas и файлом csv, из которого мне нужно агрегировать значения двух столбцов и построить их график (с помощью matplotlib). Я нашел это руководство, в котором используются groupby() иагрегат(), и оно решает первый шаг. Однако индексный столбец фрейма данных почему-то отключен, и я не могу понять, как его построить.
В учебнике используется этот код:
Код: Выделить всё
df = pd.DataFrame({'id': [101, 101, 102, 103, 103, 103],
'employee': ['Dan', 'Dan', 'Rick', 'Ken', 'Ken', 'Ken'],
'sales': [4, 1, 3, 2, 5, 3],
'returns': [1, 2, 2, 1, 3, 2]})
agg_functions = {'employee': 'first', 'sales': 'sum', 'returns': 'sum'}
df_new = df.groupby(df['id']).aggregate(agg_functions)
Код: Выделить всё
employee sales returns
id
101 Dan 5 3
102 Rick 3 2
103 Ken 10 6
Если я попытаюсь построить график зависимости идентификатора от продаж:
Код: Выделить всё
ax = df_new.plot(kind="line", x=df_new["id"], y=df_new["sales"])
Код: Выделить всё
Traceback (most recent call last):
File "/some/path/file.py", line 396, in
ax = df_new.plot(kind="line", x=df_new["id"], y=df_new["sales"])
File "/another/path/python3.10/site-packages/pandas/core/frame.py", line 3761, in __getitem__
indexer = self.columns.get_loc(key)
File "/another/path/python3.10/site-packages/pandas/core/indexes/base.py", line 3654, in get_loc
raise KeyError(key) from err
KeyError: 'id'
Если я изменю эту строку, чтобы использовать индекс:
Код: Выделить всё
ax = df_new.plot(kind="line", x=df_new.index, y=df_new["sales"])
Код: Выделить всё
Traceback (most recent call last):
File "/some/path/file.py", line 396, in
ax = df_new.plot(kind="line", x=df_new.index, y=df_new["sales"])
File "/another/path/python3.10/site-packages/pandas/plotting/_core.py", line 940, in __call__
elif not isinstance(data[x], ABCSeries):
File "/another/path/python3.10/site-packages/pandas/core/frame.py", line 3767, in __getitem__
indexer = self.columns._get_indexer_strict(key, "columns")[1]
File "/another/path/python3.10/site-packages/pandas/core/indexes/base.py", line 5876, in _get_indexer_strict
self._raise_if_missing(keyarr, indexer, axis_name)
File "/another/path/python3.10/site-packages/pandas/core/indexes/base.py", line 5935, in _raise_if_missing
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index([101, 102, 103], dtype='int64')] are in the [columns]"
Я пробовал set_index() и reset_index(), но это не имеет никакого значения. Я также пытался извлечь значения, чтобы создать совершенно новый фрейм данных, но получил те же ошибки, что и выше.
Что случилось с этим фреймом данных? И как извлечь значения из столбца странного идентификатора?