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, 2019 in Python by ana1504.k
• 7,910 points
492 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, 2019 by SDeb
• 13,300 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, 2019 in Python by Waseem
• 4,540 points
637 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
499 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 aryya
• 7,460 points
1,743 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
• 58,020 points
3,760 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
1,035 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
1,741 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, 2019 in Python by SDeb
• 13,300 points
2,194 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, 2019 in Python by SDeb
• 13,300 points
839 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP