开发者

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 t开发者_JAVA百科hat the first column in the matrix can be of the string data type while keeping all the other columns as float?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜