gpt4 book ai didi

python - 使用python提取部分数组元素

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:13 25 4
gpt4 key购买 nike

我正在努力从具有多行和多列的 csv 文件中的特定列(左侧、顶部、长度和宽度)中提取所有整数值。我已经使用 pandas 来隔离我感兴趣的列,但我坚持如何使用数组的特定部分。

让我解释一下:我需要使用带有“left, top, length and width”属性的CSV文件的列,然后获得xmin, ymin, xmax 和ymax(这些是图像中框的坐标)。此列中的一行示例如下所示:

[{"left":171,"top":0,"width":163,"height":137,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}]

我需要提取 171、0、163 和 137 来执行必要的操作来找到我的 xmax、xmin、ymax 和 ymin

上面一行是我的 pandas 数组中的一行,我如何提取运行操作所需的数字?

这是我为提取列而编写的代码,这是我目前所拥有的代码:

import os
import csv
import pandas
import numpy as np

csvPath = "/path/of/my/csvfile/csvfile.csv"

data = pandas.read_csv(csvPath)
csv_coords = data['Answer.annotation_data'].values #column with the coordinates
image_name = data ['Input.image_url'].values
print csv_coords[2]

最佳答案

使用:

import ast

d = {'Answer.annotation_data': ['[{"left":171,"top":0,"width":163,"height":137,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}]',
'[{"left":170,"top":10,"width":173,"height":157,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}]']}
df = pd.DataFrame(d)

print (df)
Answer.annotation_data
0 [{"left":171,"top":0,"width":163,"height":137,...
1 [{"left":170,"top":10,"width":173,"height":157...

#convert string data to list of dicts if necessary
df['Answer.annotation_data'] = df['Answer.annotation_data'].apply(ast.literal_eval)

对于cols的每个值,提取dict的值并返回DataFrame,最后通过concat连接在一起:

def get_val(val):
comb = [[y.get(val, np.nan) for y in x] for x in df['Answer.annotation_data']]
return pd.DataFrame(comb).add_prefix('{}_'.format(val))

cols = ['left','top','width','height']
df1 = pd.concat([get_val(x) for x in cols], axis=1)
print (df1)
left_0 left_1 top_0 top_1 width_0 width_1 height_0 height_1
0 171 222 0 42 163 45 137 70
1 170 222 10 42 173 45 157 70

关于python - 使用python提取部分数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51890489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com