使用python matplotlib,使用dataframe.groupby().mean()对数据进行分组,但无法基于分组依据列进行绘图

hgc7kmma  于 2022-11-15  发布在  Python
关注(0)|答案(1)|浏览(127)

我尝试运行以下简短的python脚本

import pandas as pd
df = pd.read_csv (r'usa survey data edited.csv')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
dfm = df.groupby("Race").mean()
ax.plot(dfm["Race"], dfm["Mortgage"])
plt.show()

当我尝试运行它时,它给出以下错误:

Traceback (most recent call last):
  File "C:\all\_sfsu\MATH 324\firstplot.py", line 6, in <module>
    ax.plot(dfm["Race"], dfm["Mortgage"])
  File "C:\Users\danta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\frame.py", line 3805, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\danta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
    raise KeyError(key) from err
KeyError: 'Race'

表示它不能根据数据分组所依据的“种族”列进行绘图。
请让我知道我如何做一个图与x轴为种族和y轴为分组的种族平均值我的抵押贷款数据。

kmpatx3s

kmpatx3s1#

我想明白了,我必须

dfm = df.groupby("Race", as_index=False).mean()

以使其停止将主列视为SQL索引。

相关问题