Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change dtype of a single column in a 2d numpy array

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?

like image 866
MedicalMath Avatar asked Oct 11 '10 07:10

MedicalMath


1 Answers

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.

like image 146
François Avatar answered Sep 23 '22 14:09

François