views:

35

answers:

1

I am creating a 2d array full of zeros with the following line of code:

MyNewArray=zeros([4,12],float)

However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data that can be manipulated mathematically.

How can I edit the code above so that the first column in the matrix can be of the string data type while keeping all the other columns as float?

+1  A: 

You might want to use structured arrays

MyNewArray = zeros(12, dtype='S10,f4,f4,f4')

There are several ways of defining the structure, here I have defined 4 fields: one text with 10 characters, and three floats (you could write float instead of f4). It is important to note that the number of characters of the array has to be specified, for array memory management reasons. You won't be able to store strings longer than this maximum length.

Each field is referenced by a field name, in this case, default field names f0 to f3 will been used. For example, to get the whole first column (the textual one):

MyNewArray['f0']

Of course, you can modifiy field names as you wish.

François
François is right. The elements of Numpy arrays must all be the same type. That requirement allows Numpy to avoid checking types on each element when performing operations. It's important to keep that in mind when using Numpy.
AFoglia