user3055163
user3055163

Reputation: 561

Numpy: concatenate different dtypes whilst preserving each dtype

I have 3 arrays which I want to concatenate along axis 1. Their dtypes are np.float32, U32 and np.float32. When I concatenate like this:

np.concatenate((A,B,C), axis=1)

the dtype of the result is 'U32'. I want preserve the float32 dtypes of columns A and C. How do I do this?

Upvotes: 2

Views: 8887

Answers (2)

user2699
user2699

Reputation: 3157

You can do this with structured arrays (or record arrays). If A, B and C are defined as

import numpy as np
A = np.zeros(30, dtype=np.float32)
B = np.zeros(30, dtype=np.int32)
C = np.zeros(30, dtype=np.float32)

You can create a record array with

res = np.rec.fromarrays([A,B,C], names='a,b,c')

A,B, and C must have the same shape, but they can have any datatype you choose. The sub-arrays (or fields) can be accessed with res.a or res['a']. Most operations (mean, max, etc.) can't operate on the whole array. You'll need to select an individual field, but indexing and related operations will work on the whole array. Structured arrays are a very useful object once you get used to working with them.

Upvotes: 5

Ali Hummos
Ali Hummos

Reputation: 19

You can create a numpy array with dtype=object. It allows you to mix types. Here is an example.

integer = [1, 5]
floats =[3., 4.]
mixed  = np.array( [integer, floats], dtype=object)
mixed 
out[4]:
array([[1, 5],
[3.0, 4.0]], dtype=object)

Upvotes: 0

Related Questions