【问题标题】:Python - KeyError: 14425LPython - 密钥错误:14425L
【发布时间】:2013-08-04 16:10:16
【问题描述】:

当我使用此代码时,它会打印一切正常,然后给我一个错误: 密钥错误:14425L 代码:

i = 0
while (i <= len(data)):
    print data.ix[i]['Params']
    i += 1

顺便说一句:

data.keys()
Out[67]: Index([u'Email Address', u'Hashed Email', u'Timestamp', u'Session Index', u'Event', u'Description', u'Version', u'Platform', u'Device', u'Params'], dtype=object)

【问题讨论】:

  • 为什么要使用显式的 while 循环遍历索引? 必须可以改用普通的for(这样可以防止此类错误,并且开销更少)。
  • data是什么类型的对象?
  • 按索引迭代是非 Python 的——它很慢,难以阅读,并且只适用于序列,而不适用于任意迭代。

标签: python keyerror


【解决方案1】:

Python 列表索引基于 0,因此 len(data) 不是有效索引。

使用

while (i < len(data)):

改为。

但是,您似乎正在循环遍历 Pandas 数据框。您可能想查看iterating row by row through a pandas dataframeWhat is the most efficient way to loop through dataframes with pandas?

【讨论】:

  • 谢谢。抱歉这个愚蠢的问题:)
【解决方案2】:

您正在访问最后一个索引之后的索引。列表的最大索引为len(data) - 1

while (i <= len(data)):

应该是:

while (i < len(data)):

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多