How to write a string to numpy array?

Question:

I have two attributes age (float) and name (string) that belongs to a person. I want to write them to csv file, hence, I used numpy to store data, then write it to csv.

import numpy as np
import random
age_name = np.empty((2, 10))
print (age_name.shape)
for i in range (10):
    age = random.randint(0,100)
    name =  'ABC'
    age_name[0,i]=age
    age_name[1,i]=name
print (age_name)

I got the error

Traceback (most recent call last):
File “python”, line 9, in
ValueError: could not convert string to float: ‘ABC’

It may be a not a good option because the data has both string and float number, could you suggest to me a good way that can easy to store to csv file?

Asked By: John

||

Answers:

Older versions of numpy had chararrays and numarrays, but now you just pass a dtype to tell numpy that the array needs to contain more than just numbers. Using dtype=str will only take one string per element, so you will get “a” “a” “a”…, instead of the whole string “abc”. To get that, you pass object as the dtype.

import numpy as np
import random
age_name = np.zeros((2, 10), dtype=object)
print (age_name)
for i in range (10):
    age = random.randint(0,100)
    name =  'ABC'
    age_name[0,i]=age
    age_name[1,i]=name
print (age_name)

>>>[[0 0 0 0 0 0 0 0 0 0]
>>> [0 0 0 0 0 0 0 0 0 0]]
>>>[[24 67 72 59 44 4 71 16 17 82]
>>> ['ABC' 'ABC' 'ABC' 'ABC' 'ABC' 'ABC' 'ABC' 'ABC' 'ABC' 'ABC']]
Answered By: user10597469

For heterogenous data (with differently typed columns, some of which contain str/object data) use pandas.DataFrames.

For data of "mixed types" where (legitimate) strings can be found within each/some column(s) interspersed with numeric values, use python dicts.

Only for uniform data (typically numeric) use numpy.ndarrays.

Answered By: mirekphd
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.