如何将方括号添加到 numpy 数组中的值

How to add square brackets to values in numpy array

下面是我的工作代码:

import numpy as np

test = [{"test":np.array([["value1,value1"],["value2,value2"]])},{"names": 
                                                        ["test1","test2"]}]
q = ["value3,value3"]
v = ["test3"]

for p in test:
    for item,value in p.items(): 
        if str(item).startswith("test"):
            p["test"] = np.append(p["test"],np.array([q]))
        

        if str(item).startswith("names"):
            for r in v:
                p["names"].append(r)

我需要如下输出:

[{'test': array([['value1,value1'], ['value2,value2'], ['value3', 'value3']], 
                                                   dtype='<U13')},
 {'names': ['test1', 'test2', 'test3']}]

但目前我的情况如下:

[{'test': array(['value1,value1', 'value2,value2', 'value3', 'value3'], dtype='<U13')},
   {'names': ['test1', 'test2', 'test3']}]

我哪里犯了愚蠢的错误?谢谢。

您需要附加到特定轴:

for p in test:
    for item,value in p.items(): 
        if str(item).startswith("test"):
            p["test"] = np.append(p['test'], [q], axis=0) # changed here
        

        if str(item).startswith("names"):
            for r in v:
                p["names"].append(r)

输出:

[{'test': array([['value1,value1'],
                 ['value2,value2'],
                 ['value3,value3']], dtype='<U13')},
 {'names': ['test1', 'test2', 'test3']}]