按教程视频照写的代码,为什么我机子上出错了?

import pandas as pd
df=pd.read_excel('p19.xlsx',index_col='ID')
print(df)
df['Total']=df[['Test_1','Test_3','Test_3']].sum(axis=1)
df['Average']=df[['Test_1','Test_3','Test_3']].mean(axis=1)
print(df)
col_mean=df[['Test_1','Test_3','Test_3','Total','Average']].mean()
col_mean['Name']='Summary'
print(col_mean)
df=df.append(col_mean,ignore_index=True)
print(df)

运行结果信息如下:
Name Test_1 Test_2 Test_3
ID
1 Student_001 62 86 83
2 Student_002 77 97 78
3 Student_003 57 96 46
Name Test_1 Test_2 Test_3 Total Average
ID
1 Student_001 62 86 83 228 76.000000
2 Student_002 77 97 78 233 77.666667
3 Student_003 57 96 46 149 49.666667
Test_1 65.333333
Test_3 69.0
Test_3 69.0
Total 203.333333
Average 67.777778
Name Summary
dtype: object
Traceback (most recent call last):
File “D:/pyobject/bili-pandas/p19 叩开统计大门把函数一网打尽 求和求平均/p19.py”, line 10, in
df=df.append(col_mean,ignore_index=True)
File “D:\pyobject\venv\lib\site-packages\pandas\core\frame.py”, line 8943, in append
other.reindex(combined_columns, copy=False)
File “D:\pyobject\venv\lib\site-packages\pandas\core\series.py”, line 4580, in reindex
return super().reindex(index=index, **kwargs)
File “D:\pyobject\venv\lib\site-packages\pandas\core\generic.py”, line 4819, in reindex
axes, level, limit, tolerance, method, fill_value, copy
File “D:\pyobject\venv\lib\site-packages\pandas\core\generic.py”, line 4843, in _reindex_axes
allow_dups=False,
File “D:\pyobject\venv\lib\site-packages\pandas\core\generic.py”, line 4889, in _reindex_with_indexers
copy=copy,
File “D:\pyobject\venv\lib\site-packages\pandas\core\internals\managers.py”, line 670, in reindex_indexer
self.axes[axis]._validate_can_reindex(indexer)
File “D:\pyobject\venv\lib\site-packages\pandas\core\indexes\base.py”, line 3785, in _validate_can_reindex
raise ValueError(“cannot reindex from a duplicate axis”)
ValueError: cannot reindex from a duplicate axis

Process finished with exit code 1

讨论数量: 3

百度一下ValueError:那一行

4周前 评论

Replace ['Test_1','Test_3','Test_3'] with ['Test_1','Test_2','Test_3']

4周前 评论
xmlhwl (楼主) 4周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!