Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add square brackets to values in numpy array

Below is my working code:

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)

I need output as following:

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

but currently im getting like below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Where am I doing silly mistake ? Thank you.

>Solution :

Your need to append to a specific axis:

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)

output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading