nickanna_42
nickanna_42

Reputation: 179

Error setting dtypes of an array

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

Upvotes: 2

Views: 912

Answers (1)

Mehdi
Mehdi

Reputation: 679

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)

Upvotes: 2

Related Questions