python - ValueError : Length mismatch: Expected axis has 2 elements, new values have 3 elements

标签 python pandas syntax-error data-visualization pie-chart

这是我计划用于创建饼图的代码。

import csv
with open('C:\\Users\Bhuwan Bhatt\Desktop\IP PROJECT\Book1.csv', 'r') as file :
    reader = csv.reader(file)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def piechart1():
   df=pd.read_csv('data,csv',  sep=' ', index_col=False,skipinitialspace=True\
                 ,error_bad_lines=False,encoding= 'unicode_escape')
   df=df.set_index(['Country'])
   dfl=df.iloc[:,[14]]
   final_df=dfl.sort_values(by='TotalMedal')
   final_df.reset_index(inplace=True)
   final_df.columns=('location','Total cases','Total Deaths')
   final_df=final_df.drop(11,axis='index')
   countries=df['Country']
   tmedals=df['TotalMedal']
   plt.pie(tmedals,labels=countries,explode=(0.1,0,0,0,0,0,0,0,0,0,0.2),shadow=True,autopct='%0.1f%%')
   plt.title("Olympics data analysis\nTop 10 Countries", color='b',fontsize=12)
   plt.gcf().canva.set_window_title("OLMPICS ANALYSIS")
   plt.show()
由于某种原因,我收到此错误:
AttributeError: 'DataFrameGroupBy' object has no attribute 'sort_values'
这是我一直在使用的CSV文件:
Country SummerTimesPart Sumgoldmedal    Sumsilvermedal  Sumbronzemedal  SummerTotal WinterTimesPart Wingoldmedal    Winsilvermedal  Winbronzemedal  WinterTotal TotalTimesPart  Tgoldmedal  Tsilvermedal    Tbronzemedal    TotalMedal
     Afghanistan    14  0   0   2   2   0   0   0   0   0   14  0   0   2   2
     Algeria    13  5   4   8   17  3   0   0   0   0   16  5   4   8   17
     Argentina  24  21  25  28  74  19  0   0   0   0   43  21  25  28  74
     Armenia    6   2   6   6   14  7   0   0   0   0   13  2   6   6   14

INFO-----> SummerTimesPart  :  No. of times participated in summer by each country
           WinterTimesPart  :  No. of times participated in winter by each country

最佳答案

在您的代码中,将Country设置为Index,并在此行中

dfl=df.iloc[:,[14]]
您只需选择一列TotalMedal即可。
排序并重置索引后,您尝试按行更改列名称
final_df.columns=('location','Total cases','Total Deaths')
这是错误。.您仅过滤了一列的数据框,并且在重置后在列中也获得了Country。因此,您在数据框中只有两列,并尝试通过提供三个值来更改列名称。
正确的行可能是-
final_df.columns=('location','TotalMedal')

关于python - ValueError : Length mismatch: Expected axis has 2 elements, new values have 3 elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63656186/

相关文章:

python - 使用折叠相关参数对 GridSearchCV 进行自定义评分

c# - .NET 的 Python : How to explicitly create instances of C# classes using different versions of the same DLL?

python - 按 multiIndex 之一的最高分位数过滤数据帧行

python - 打开两个文件时 with 语句中的 SyntaxError

json - 如何调用循环返回 JSON 的 URL

python - 如何在 PyDev 中禁用模板调试

python - 带有掩码和变换的 Groupby

python - 在 Pandas 中匹配来自excel的索引函数

Python导入CSV排序代码( Pandas ?)在条目中用 ';'和 ','分隔

堆栈上的 C++ 编程书籍示例