1

When I append elements to a list that have the following format and type:

data.append([float, float, string])

Then stack the list using:

data = np.hstack(data)

And then finally reshape the array and transpose using:

data = np.reshape(data,(-1,3)).T

All the array elements in data are changed to strings. I want (and expected) the first and second columns in data to be of type float and the third of type string, but instead they are all of type string. [Interestingly, if I do not append the string elements to data and adjust the newshape to (-1,2), both columns are floats.] I cannot figure this one out. Any help would be appreciated.

2
  • I think as soon as numpy touches it it converts them to a common format unless told otherwise. I don't know if you can tell it dtypes with hstack, but here is an alternative: stackoverflow.com/questions/26018781/… Commented Oct 18, 2018 at 14:56
  • Markus, thanks for the help. Your comments guided me to this: stackoverflow.com/questions/42813011/… I was able to find a solution here using dtype=object. Commented Oct 18, 2018 at 18:24

1 Answer 1

1

Because of the mix of numbers and strings, np.array will use the common format: string. The solution here is to convert data to type object which supports mixed element types. This is performed by using:

data = np.array(data, dtype=object)

prior to hstack.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.