【问题标题】:KeyError: 'Tipos' During handling of the above exception, another exception occurred: Traceback (most recent call last):KeyError: 'Tipos' 在处理上述异常的过程中,发生了另一个异常: Traceback(最近一次调用最后一次):
【发布时间】:2020-09-20 05:02:53
【问题描述】:

Pandas 太难了,我重新检查了一百万次,我的 Python 文件和 csv 确实在同一个文件夹中。

import pandas as pd
import matplotlib.pyplot as plt

plt.subplot(131) #Numero de choques por estado al mes
estados = ['NL','COAH','EDOMEX','VER','TAMP']
choques = [12000, 7600, 9500, 3000, 5430]
plt.title ("Numero de choques por estado al mes")
plt.xlabel ('Estados')
plt.ylabel ('choques')
plt.bar(estados, choques, color = 'green')
plt.plot(estados, choques,"r:*")
plt.xticks (rotation=45, fontsize=6)
plt.subplot(132) #grafica tips de accidentes

Tipos = {'tipos' : ['choque','atropellamiento','volcamiento','otro'],
'numeros': [752, 230,365,155]}
df=pd.DataFrame(Tipos)
plt.scatter(df['tipos'], df['numeros'])
plt.xticks(rotation=45)
plt.ylabel ('Accidentes Numero de Accidentes en Nuevo Leon')
plt.xlabel ('Tipos')
plt.title ('Numero de Accidentes en Nuevo Leon')
plt.subplot(133)

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

plt.title('tipos de vehiculos y numero de accidentes')
plt.plot (df['Tipos'], df['Numero'],'r*:')
plt.xticks(rotation=35, fontsize=6)
plt.xlabel('Tipos')
plt.yticks(rotation=35, fontsize=6)
plt.ylabel('Numeros')
plt.legend(['Tipos','Numeros'])
plt.tight_layout()
plt.show()

【问题讨论】:

  • 你得到什么错误?相对路径是相对于您的当前工作目录。它相对于脚本的位置。
  • 如果您从与文件相同的位置运行脚本,请尝试:os.path.join(os.getcwd(), 'tiposdevehiculos.csv') 作为 CSV 的文件路径
  • 您显示的错误消息的一部分似乎表明您阅读了 csv 文件没有问题,但没有确切名称为 'Tipos' 的列(可能是小写?也许没有's'?也许完全不同?)。您可能想在阅读后向我们展示调用tiposdevehiculos.head() 的输出。您可能还想显示完整的错误消息和跟踪,包括指出该行及其引用的命令。

标签: python pandas csv dataframe matplotlib


【解决方案1】:

创建 DataFrame (df) 后,添加:

print(df.columns)

并查看列名。很可能您的 DataFrame 没有 名为提示的列。

此类错误的一个可能原因是 CSV 文件中的标题行 包含空格,例如:

id, Tipos, numeros,...

对于阅读这个文件的人来说这是很自然的,但对于计算机来说却不是。

在这种情况下,您的 DataFrame 的列名称为 ' Tipos'带有前导 空格,但没有'Tipos' 列。需要一些经验 知道要寻找什么(其中包括此类细节)。

另一个更正是:

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

只写:

df = pd.read_csv('tiposdevehiculos.csv')

创建一个 DataFrame 没有意义(从 CSV 文件中读取) 然后从中创建另一个 DataFrame (df)。

还有一个提示:您的前 2 张图片创建时没有错误。 所以问这个问题你应该只包括关于 第三张图片,即使没有plt.subplot(133)。 只是关于这张单张图片的代码。

最后一个重要细节:您的堆栈跟踪肯定包含精确的 指示哪一行代码引发了此异常。你应该有 也包括在内。

【讨论】:

    【解决方案2】:

    很难说发生了什么,你在哪一行得到错误?听起来像“Tipos”列只是不存在于您尝试使用的数据帧之一中。只需打印数据框即可帮助您了解其中的内容:

    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2019-09-25
      • 2021-02-08
      相关资源
      最近更新 更多