Pandas Multi–Column Pie Plot with "TypeError: Int64Index.name must be a hashable type"

Pandas Multi–Column Pie Plot with "TypeError: Int64Index.name must be a hashable type"

我对编码很陌生,这似乎是我不理解的 Python/Pandas/Matplotlib 的一些基本方面。我对一般答案很满意,但是,作为参考,这里是我的具体上下文:

top_100.index = top_100.Company
top_100 = top_100.dropna()
top_20 = top_100[(top_100.Rank > 10) & (top_100.Rank < 21)]
top_20 = top_20.sort_values('Rank', ascending = True)
top_20.index = top_20.Rank
plt.figure()
top_20.plot.pie(y = ['USA_Retail_Sales_million',\
                     'Worldwide_Retail_Sales_million'], subplots = True,\
                figsize = (16, 8), autopct = '%1.1f%%', legend = False)
plt.show()

完整的错误消息如下:

runcell(65, 'C:/Users/Adam/Desktop/DSCI 200/Practice/Wk 3 Practice.py')
Traceback (most recent call last):

  File "C:\Users\Adam\Desktop\DSCI 200\Practice\Wk 3 Practice.py", line 359, in <module>
    top_20.plot.pie(y = ['USA_Retail_Sales_million',\

  File "C:\Users\Adam\anaconda3\lib\site-packages\pandas\plotting\_core.py", line 1528, in pie
    return self(kind="pie", **kwargs)

  File "C:\Users\Adam\anaconda3\lib\site-packages\pandas\plotting\_core.py", line 908, in __call__
    data.index.name = y

  File "C:\Users\Adam\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 1190, in name
    maybe_extract_name(value, None, type(self))

  File "C:\Users\Adam\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 5665, in maybe_extract_name
    raise TypeError(f"{cls.__name__}.name must be a hashable type")

TypeError: Int64Index.name must be a hashable type

<Figure size 432x288 with 0 Axes>

不管它值多少钱,我都没有接近 5600 行代码。

每次我 运行 这个代码,我都会得到 TypeError: Int64Index.name must be a hashable type。我已经多次更改索引,但已经意识到我不认为问题出在我的索引上;我显然要求它更改不可变的 'something'。我只是不知道 'something' 是什么,或者如何解决这个问题。也许(显然)我对 Int64Index.name 是什么以及我要它做什么有一个非常初步的理解。我当然没有断定我的代码完全错误,但 似乎 对我来说是正确的 - 这一点也不值钱。

我用以下最小示例重新创建了问题(使用 Pandas 1.2.0):

import pandas as pd
import matplotlib.pyplot as plt

# randomly made up data
top_20 = pd.DataFrame(
    {'USA_Retail_Sales_million': [0.330, 4.87 , 5.97],
     'Worldwide_Retail_Sales_million': [2439.7, 6051.8, 6378.1]},
)
top_20.plot.pie(
    y=['USA_Retail_Sales_million', 'Worldwide_Retail_Sales_million'],
    subplots=True, figsize=(16, 8), autopct='%1.1f%%', legend=False
)
plt.show()

上面的代码产生了同样的错误。 pie 函数根本不接受 lists/tuples 作为 y 参数。正确的方法是使用用于绘图的列创建一个新的 DataFrame。

import pandas as pd
import matplotlib.pyplot as plt


top_20 = pd.DataFrame(
    {'USA_Retail_Sales_million': [0.330, 4.87 , 5.97],
     'Worldwide_Retail_Sales_million': [2439.7, 6051.8, 6378.1]},
)
new_df = top_20[['USA_Retail_Sales_million', 'Worldwide_Retail_Sales_million']]
new_df.plot.pie(subplots=True, figsize=(16, 8), autopct='%1.1f%%', legend=False)
plt.show()