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
• 6,110 points
4 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 9,660 points

Related Questions In Python

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
12 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,320 points
200 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,120 points
344 views
0 votes
1 answer

What's the canonical way to check for type in Python?

To check if o is an instance ...READ MORE

answered Aug 24, 2018 in Python by Priyaj
• 56,120 points
14 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
34 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
61 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
• 9,660 points
7 views
0 votes
1 answer

Python sort() function arguments

Both sort and sorted have three keyword arguments: cmp, key and reverse. L.sort(cmp=None, key=None, reverse=False) -- ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 9,660 points
137 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.