Pandas的 aggregate() 会生成一个很奇怪的DataFrame

编程语言 2026-07-10

我已经为这个问题头疼很久了,但在网上找不到答案,希望有人能给点线索。

我在使用Pandas和一个csv文件,需要对两列的值进行聚合并把它们绘制出来(用matplotlib)。我找到了这篇教程,它使用groupby() 和aggregate(),并解决了第一步。但是dataframe的索引列似乎有点问题,我似乎搞不清楚如何绘制它。

在教程中,使用了如下代码:

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)

...新DataFrame看起来是这样的:

    employee  sales  returns
id  
101      Dan      5        3
102     Rick      3        2
103      Ken     10        6

id列看起来不一样。我的数据也有同样的问题。

如果我尝试绘制id与 sales:

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 <module>
    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'

所以Pandas找不到 '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 <module>
    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(),但没有任何变化。我也尝试提取值来创建一个全新的DataFrame,但得到的错误和上面一样。

这张数据帧到底发生了什么?如何从这颗怪异的id列中提取数值?

解决方案

Pandas默认将索引设为你的分组列。为了避免这种情况,请传入 as_index=False 或在事后执行 reset_index()。此外,当你对DataFrame调用plot时,pandas期望列名是字符串。当你执行 x=df_new["id"] 时,你传入的是一个Series。

完整可运行示例

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('id', as_index=False).agg(agg_functions)
ax = df_new.plot(kind="line", x="id", y="sales")
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章