python - 数据编码为字符串时出现 KeyError

标签 python pandas matplotlib types

在与绘图代码斗争之后,我最终得到了以下最小工作示例:

import pandas
import matplotlib.pyplot as plt

data = {
    'foo': ['2', '335', '3'],
    'bar': [1, 2, 1],
}

pandas.DataFrame(data).plot.scatter('foo', 'bar')  # KeyError
plt.show()

引发 KeyError: 'foo'

但是,如果我在 foo 数据中使用整数而不是字符串:

'foo': [2, 335, 3],

我得到了预期的散点图,没有错误。

此 DataFrame 行为的基本原理是什么? 我可以理解所有数据必须采用相同的格式。但为什么在这种情况下引发(非常简洁的)KeyError?

最佳答案

在较新的版本中不再是这种情况。

现在引发的错误是:ValueError: scatter requires x column to be numeric,这是一个信息量更大的错误。

无论如何,我假设原始 KeyError 的原因是使用了内部函数 _get_numeric_data(在父类(super class) NDFrame 下) ) 在绘图函数中。这会在尝试绘制之前删除非数字列,从而引发 KeyError,因为非数字列“foo”已被删除。

关于python - 数据编码为字符串时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374153/

相关文章:

python - 如何显示用户是否已经喜欢 Django 中的对象实例

python - 使用 model.predict() 时出现错误 "converting string to float"

python - Pandas 中的列名浮点为整数

python - Python中的ggplot样式

python - 强调图像中的蓝色

python - 用于客户端 python 接口(interface)/raw_input 的 Twisted Reactor

python - 如何诊断两台机器之间 Python 脚本(pandas 聚合)运行时的巨大差异?

Python/ Pandas : Finding index for the nlargest and keeping only those above a value

python - Matplotlib 干扰图奇怪的图案

python - 在新编译的 python 上安装 pip