python pandas:块状大小如何工作?
我有以下代码:
from numpy import dtype
import pandas as pd
import os
import sys
inputFile='data.json'
chunks = pd.read_json(inputFile, lines=True, chunksize = 1000)
original_stdout = sys.stdout
i = 1
for c in chunks:
location = c.location.str.split(',')
for b in range(1000):
print(location[b])
if not type(location[b]) == float:
# get the country name
country = location[b][-1]
else:
country = 'unknown'
我正在从包括JSON对象的大文件中提取位置字段。因为文件太大,所以我将其分为1000行的块。我循环浏览每个块并检索所需的信息:
for c in chunks:
location = c.a.str.split(',')
for b in range(1000):
print(location[b])
在第一次迭代期间,一切都顺利进行。在第二次迭代中,行:
print(location[b])
给出错误:
ValueError: 0 is not in range
如何在第一个之后循环凹槽?
感谢您的帮助
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,通过做
位置[B]
,您正在访问indote
frame index (即,您在这里要求使用该行索引值b
)。这些块将正确遵循索引,这意味着第一个块将以0
开始,第二个块由1000
,等等。这意味着,索引0
仅包含在第一个块中。因此,相反,您需要在没有索引的情况下迭代行:
实际上,如果您查看错误的完整跟踪,您还将在
value> value> value> value> value> keyError
>。要迭代系列并具有索引,您可以使用 :
The problem is that by doing
location[b]
you are accessing thelocation
frame by index (i.e., here you are asking for the row with the index valueb
). The chunks will follow the index correctly, which means the first chunk will have the index starting by0
, the second by1000
, and so on. This means, index0
will only be contained in the first chunk.So, instead, you need to iterate the rows without the index:
In fact, probably if you look at the full trace of the error you will also see a
KeyError
below theValueError
.To iterate the Series and have the index you can use
Series.iteritems()
: