我们有 1000 行,在 CSV 文件中存储相同的信息,存储在一列中,如下所示。我们如何循环它并在 python 中获取属性 x、y、高度和宽度?
[{"task":"T0","task_label":"Draw a box around each person name and transcribe their information.","value":[{"x":224.63333129882812,"y":89.96666717529297,"tool":0,"frame":0,"width":333.9999694824219,"height":42.00000762939453,"details":[{"value":"Rev. Leopold Wyke Acland"},{"value":0}],"tool_label":"Tool name"},{"x":95.63333129882812,"y":55.96666717529297,"tool":0,"frame":0,"width":280,"height":37,"details":[{"value":"Acland, Thomas Wyke"},{"value":0}],"tool_label":"Tool name"}]}]
如果所有行的格式相同,则可以循环访问行并捕获列表中的值,如下所示:
x, y, height, width = list(), list(), list(), list()
for row in rows:
x.append(row[0]["value"][0]["x"])
y.append(row[0]["value"][0]["y"])
height.append(row[0]["value"][0]["height"])
width.append(row[0]["value"][0]["width"])
您可以将捕获的值存储为字典,然后轻松转换为熊猫数据帧:
d = {"x": x, "y": y, "height": height, "width": width}
df = pd.DataFrame(data=d)
由于最外层的list
只包含一个对象,即 3 个字段
-
task
不需要。 -
task_label
不需要。 -
value
我们感兴趣的一个。
在给定的上下文中,我们可以通过以下方式遍历dict
for item in data[0]["value"]:
print(f"x = {item['x']}")
print(f"y = {item['y']}")
print(f"width = {item['width']}")
print(f"height = {item['height']}")
您还可以以更pythonic的方式收集这些值,然后迭代生成的字典列表
result = [
{
"x": item["x"],
"y": item["y"],
"width": item["width"],
"height": item["height"]
}
for item in data[0]["value"]]
我建议在python中经历迭代。此外,此代码段假定所有行都具有统一的结构。
https://wiki.python.org/moin/ForLoop
如果外部列表确实只包含 1 个元素,则所有内容都在l[0]['value']
:
In [14]: pd.DataFrame(l[0]['value']).iloc[:, :6]
Out[14]:
x y tool frame width height
0 224.633331 89.966667 0 0 333.999969 42.000008
1 95.633331 55.966667 0 0 280.000000 37.000000
如果实际上有多个条目,您可以一次转换一个并使用pd.concat
:
In [16]: pd.concat([pd.DataFrame(v['value']).iloc[:, :6] for v in l*3]).reset_index(drop=True)
Out[16]:
x y tool frame width height
0 224.633331 89.966667 0 0 333.999969 42.000008
1 95.633331 55.966667 0 0 280.000000 37.000000
2 224.633331 89.966667 0 0 333.999969 42.000008
3 95.633331 55.966667 0 0 280.000000 37.000000
4 224.633331 89.966667 0 0 333.999969 42.000008
5 95.633331 55.966667 0 0 280.000000 37.000000