Skip to main content
 首页 » 编程设计

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

2024年12月31日8xiaohuochai

我正在努力从具有多行和多列的 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