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

Add a string to a NumPy array

I made an array for a contact list:

data = np.array([
    ["Leon","John","Petar"], #Names
    ["Smith","Jones","Taylor"], #Surnames
    ["leon.smith@gmail.com","john.jones@chello.at","peta.tayl@gmail.com"], # EMails
    ["maxefaxe11","Mohrhuhn3000","warpd_fungz"], #Usernames
    ["fakemake11","ichliebehuhn1","lollls123"] #Passwords
])

Then I tried coding a registration, that inserts new contacts to the array, to transform the array to this:

["Leon","John","Petar","Tom"], 
["Smith","Jones","Taylor","Walker"], 
["leon.smith@gmail.com","john.jones@chello.at","peta.tayl@gmail.com","tom.tow@gmail.com"], 
["maxefaxe11","Mohrhuhn3000","warpd_fungz","tomi12341"], 
["fakemake11","ichliebehuhn1","lollls123","password111"]

I tried this code to insert the new contact:

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

def register_contact():
    # Prompt user for details
    name = input("Enter name: ")
    surname = input("Enter surname: ")
    email = input("Enter email: ")
    username = input("Enter username: ")
    password = input("Enter password: ")

    # Add the new contact to the data array
    new_contact = np.array([[name, surname, email, username, password]])
    global data
    data = np.concatenate((data, new_contact), axis=1)

    print("Contact registered successfully.")

register_contact()
# Check the updated data
print(data)

But it said:
"ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 5 and the array at index 1 has size 1"

>Solution :

The problem is that you don’t have a list of contacts ([contact1, contact2, contact3, ...]), you have a list of contact fields ([names, surnames, emails, ...]). So to add a new contact you must append each field of the new contact to its respective array.

You can do so with transpose, turning new_contact rows into columns:

data = np.concatenate((data, new_contact.transpose()), axis=1)
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