0

I would like to give an existing numpy array named columns. I've tried to name the columns in the following way:

X = np.random.normal(0,1,(3,3))
names = ['a','b','c']
types = ['f4']*len(names)
t = list(zip(names,types))

Y= np.array(X, dtype=t)

However, when I call Y['a'], I am given a 3x3 array rather than the first column of X, which is 3x1.

How can I give an existing array named columns? What is my error in my example?

2
  • Watch out, np.random.normal probably returns f8 Commented May 14, 2017 at 1:51
  • Sometimes the X.tolist() is needed as an intermediate form. But it might also need to be converted to a list of tuples Commented May 14, 2017 at 1:58

1 Answer 1

3

You're looking for .view, which reinterprets existing memory in a new way.

names = ['a','b','c']
types = [X.dtype]*len(names)
t = list(zip(names,types))
Y = X.view(t)

For this to work, you need to match the dtype of X - f4 is probably not correct.

Your code is equivalent to X.astype(t). When converting to a struct array, that tries to set every field to the same value.

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

1 Comment

Great, it looks like veiw is what I need. i'll read the docs to ensure I use it correctly.

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.