首页 > 解决方案 > 如何修复“ValueError:长度不匹配”

问题描述

我收到一个错误:

ValueError: Length mismatch: Expected axis has 5 elements, new values have 6 
elements

当我运行我的基本代码时:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd 

READ = "C:\\Users\\Ashley\\Biotech Data Center 4.1.21.xlsx"

stocks = "BHVN"

PipelineData = pd.read_excel(READ, sheet_name='Sheet1', header=None, index_col=0)
pipelinecolstitle = pd.read_excel(READ, sheet_name='Sheet1', header=None,nrows=1).values[0]
PipelineData.columns = pipelinecolstitle
colspipe= ['Catalyst']
tt = PipelineData[colspipe]

for i in stocks:
    t = tt.loc[(PipelineData['Ticker']==i)]
    print(t)
    
    fig, ax = plt.subplots()
    cols = ["Catalyst"]

    axMain = plt.subplot(2,1,1)
    table = plt.subplot(2,1,2, frameon=False)

    axMain.plot([1,2,7])
    table = ax.table(cellText=t, loc='upper center',colLabels=cols)
    table.axis("off")

plt.show()

似乎它不喜欢 index_col=0 如果我更改 index_col=None 它会给我一个 KeyError: 0

标签: pythonexcelpandas

解决方案


这个错误可能是由这个 assignment 引发的,这PipelineData.columns = pipelinecolstitle意味着PipelineData的列数不等于pipelinecolstitle长度。

检查PipelineData.shape[1] == len(pipelinecolstitle)


推荐阅读