python structured/recarray type conversion behaviour

0 votes
The behaviour of type conversion is pretty confusing when constructing a structured/recarray:

For example, the following code takes in numerical fields but defines the type as string:

data = [(1.0, 2), (3.0, 4)]
np.array(data, dtype=[('x', str), ('y', int)])
 

Which produces:

array([('', 2), ('', 4)], dtype=[('x', 'S'), ('y', '<i8')])
 

So the values were converted to empty strings which is not what you would expect from:

str(1.0)
 

Which produces the string '1.0'. Can anyone tell me the problem and how to solve this?
May 15 in Python by ana1504.k
• 7,870 points
18 views

1 answer to this question.

0 votes
You need to specify a string width, e.g. 'a3':

>>> np.array([(1.0, 2),(3.0,4)],dtype=[('x','a3'),('y',int)])
array([('1.0', 2), ('3.0', 4)],
      dtype=[('x', 'S3'), ('y', '<i4')])
 

Just using str effectively means a string field of 0 bytes - which of course is too small to hold the string rendition of the float.
answered May 15 by SDeb
• 13,160 points

Related Questions In Python

0 votes
0 answers

How is type conversion done in python?

How do you convert a list to ...READ MORE

Sep 3 in Python by Waseem
• 4,480 points
15 views
0 votes
1 answer

Type checking in Python

Use the type() function with the variable ...READ MORE

answered May 8, 2018 in Python by Nietzsche's daemon
• 4,260 points
26 views
0 votes
1 answer

Can someone explain the behaviour of increment and decrement operators in python

down voteaccepted ++ is not an operator. It is ...READ MORE

answered May 15, 2018 in Python by ariaholic
• 7,340 points
424 views
0 votes
1 answer

Behaviour of increment and decrement operators in Python

When you want to increment or decrement, ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 56,900 points
909 views
+1 vote
2 answers

View onto a numpy array?

 just index it as you normally would. ...READ MORE

answered Oct 18, 2018 in Python by roberto
53 views
0 votes
1 answer
0 votes
1 answer

Printing a large numpy array

numpy.set_printoptions(threshold='nan') READ MORE

answered Jul 20, 2018 in Python by Nietzsche's daemon
• 4,260 points
115 views
0 votes
1 answer

How to get base class type in Python?

Yes, There is an alternative. You can ...READ MORE

answered Feb 8 in Python by SDeb
• 13,160 points
21 views
0 votes
1 answer

When to use super(type) in python?

super(x) returns an "unbound" descriptor, that is, ...READ MORE

answered Jun 3 in Python by SDeb
• 13,160 points
29 views