You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas报ValueError、KeyError及matplotlib.pyplot运行报错问题求解

报错原因分析及解决方案

1. ValueError: Columns must be same length as key 报错原因与修复

错误原因

df.sort_values('Time', ascending=True)执行后返回的是排序后的完整DataFrame(包含Time、Close两个列),你将双列的二维对象赋值给df['Time']单个列,维度不匹配触发报错。

修复方案

直接将排序结果赋值给整个df即可,无需仅赋值给Time列:

# 修正前错误代码
# df['Time'] =  df.sort_values('Time', ascending=True)
# 修正后代码
df = df.sort_values('Time', ascending=True)

2. KeyError: 'Time' 报错原因与修复

错误原因

你执行了df = df.set_index(['Time'])操作,该操作会把Time列从普通数据列转换为索引,df的普通列列表中不再存在Time这个key,直接用df['Time']取值会触发键不存在的报错。
另外原标题代码还存在括号位置错误:plt.title的闭合括号放在了字符串拼接中途,会触发语法错误。

修复方案

取时间值直接从索引df.index中获取,同时修正括号位置:

# 修正前错误代码
# plt.title('Gold' + str(np.min(df['Time']))) + str(np.max(df['Time']))
# 修正后代码
plt.title('Gold' + str(np.min(df.index)) + str(np.max(df.index)))

完整可运行代码

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

df = {
    'Time': ['2021-07-06 20:51:00', '2021-07-06 20:52:00', '2021-07-06 20:53:00'],
    'Close': ['0.068029', '0.06805', '0.068014']
}

df = pd.DataFrame(df)
df['Time'] = pd.to_datetime(df['Time'])

# 修正排序逻辑
df = df.sort_values('Time', ascending=True)
df = df.set_index(['Time'])
df = df.dropna(how='any')

fig, ax = plt.subplots(figsize=(16, 8))
plt.plot(df.index, df['Close'], label="graph", color='gold')
# 修正标题取值与括号问题
plt.title('Gold' + str(np.min(df.index)) + str(np.max(df.index)))
plt.legend()
plt.show()

内容的提问来源于stack exchange,提问作者Ahmed Nishaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:06:02