簡體   English   中英

將數據追加到數組的“右”列和行(在Python中)

[英]Appending data to the 'right' column and row of an array (in Python)

這個想法是創建一個數組,其中第一個原始數據中的值對應於管理單元的ID。 第一列對應於該管理單元內圖像的標簽。 每個圖像都有幾個標簽。 因此,其想法是檢查是否已將任何標簽附加到數組中,如果它們是首次出現,則我將其附加。 如果該標簽比之前出現的要早,則該標簽和管理單元ID的交集上的元素應增加1(對於首次出現的情況也是如此)。 我已經在這部分上了。 因此,假設管理單元的ID為1、36、15、20、16、3。我知道,現在我在ID為=的管理單元中分析標簽為“獅子,牛,貓,熊貓”的圖像36.在我之前帶有“門”標簽的某個地方,該標簽在不同的管理部門中多次出現。 所以我想有一個數組,它看起來像:

[0, 1, 36, 15, 20, 16, 3],
['door', 5, 0, 0, 4, 0, 1],
['lion', 0, 1, 0, 0, 0, 0],
['cow', 0, 1, 0, 0, 0, 0],
['cat', 0, 1, 0, 0, 0, 0],
['panda', 0, 1, 0, 0, 0, 0]

到目前為止,我有空間部分,並且:

import numpy as np
tags_array = []
np.asarray(tags_array)
tags_array[0:] = [1, 36, 15, 20, 16, 3]
tags = 'lion,cow,cat,panda'
tags_sep = tags.split(',')
my_id = 36
for tag in tags_sep:
    #if tag is not yet in the array
    tags_array.append(tag) #to the first column
    tags_array.append(1) #to the column with the first row equal to 36
    #else add +1 to the element in the column 36 and row of the tag

任何提示都非常感謝!

如果您使用字典,則更加容易,然后可以輕松將其更改為所需的數組:

tags = 'lion,cow,cat,panda'.split(",")
id = 36

for i in range(len(tags)):
    if not id in ids:
        ids = np.append(ids, id)
        for key in dico.keys():
            dico[key] = np.append(dico[key], 0)

    if not tags[i] in dico.keys():
        dico[tags[i]] = np.zeros(len(ids)).astype(int)
        dico[tags[i]][int(np.where(ids==id)[0])] = 1
    else:
        dico[tags[i]][int(np.where(ids==id)[0])] += 1

當然,在您定義帶有標簽的dico作為鍵之前:

dico={}
dico['door'] = [5, 0, 0, 4, 0, 1]
dico['lion'] = [0, 0, 0, 0, 0, 0]
dico['cow'] = [0, 0, 0, 0, 0, 0]
dico['cat'] = [0, 0, 0, 0, 0, 0]
dico['panda'] = [0, 0, 0, 0, 0, 0]

ids

ids = np.array([1, 36, 15, 20, 16, 3])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM