2

I was attempting to make a 1x5 numpy array with the following code

testArray = np.array([19010913, "Hershey", "Bar", "Birthday", 12.34])

but encountered the unwanted result that

testArray.dtype
dtype("<U8")

I want each column to be a specific data type, so I attempted to input this

testArray = np.array([19010913, "Hershey", "Bar", "Birthday", 12.34],
    dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f10')] )

but got the error

/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py:1:
DeprecationWarning: Specified size is invalid for this data type.
Size will be ignored in NumPy 1.7 but may throw an exception in
future versions. if __name__ == '__main__':
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-d2c44d88c8a5> in <module>()
----> 1 testArray = np.array([19840913, "Hershey", "Bar",
"Birthday", 64.25], dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'), ('f3','<U64'),('f4','<f10')] )

TypeError: 'int' does not support the buffer interface

1 Answer 1

2

First off, I am not sure if f10 is something known.

Note that structured arrays need to be defined as "list of tuples". Try the following:

testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34)],
dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f8')])

See also this and this for different ways of defining np.dtypes and structured arrays.

Edit:

For multiple rows in the same structure, define each row of your array as a separate tuple in the list.

dt = np.dtype([('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U‌64'),('f4','<f8')])

testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34), (123, "a", "b", "c", 56.78)], dtype=dt)
Sign up to request clarification or add additional context in comments.

5 Comments

How would I make a 2x5 numpy array with each column having its own data type, as opposed to making an flat array of lists of tupple
You can have 5 columns of the same dtype, or 5 fields with different dtypes, but not both.
Just define each row of your array as a separate tuple in the list:
dt = np.dtype([('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f8')])
testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34), (123, "a", "b", "c", 56.78)], dtype=dt)

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.