0

I have a numpy.ndarray having dimensions of 23411 x 3. I would like to add headers to the top of the matrix called: "summary", "age", and "label". In that order.

In:

matrix.shape

Out:

(23411L, 3L)

In:

type(matrix)

Out:

numpy.ndarray

I tried using the numpy.recarray but it did not work. any suggestions??

1
  • how did you try recarray? I can construct a structured array, but the process isn't trivial. And result isn't just added headers. What would you do with the array and headers? Commented Mar 1, 2018 at 19:23

4 Answers 4

4

You can achieve this with pandas.

import pandas as pd
matrix = [...] # your ndarray

matrix = pd.DataFrame(data=matrix, columns=["summary", "age", "label"])
Sign up to request clarification or add additional context in comments.

Comments

4

You can fiddle the dtype:

>>> a = np.arange(12).reshape(4, 3)
>>> 
>>> dt = a.dtype
>>> 
>>> ahead = a.view(np.dtype([('summary', dt), ('age', dt), ('label', dt)]))
>>> 
>>> ahead
array([[(0,  1,  2)],
       [(3,  4,  5)],
       [(6,  7,  8)],
       [(9, 10, 11)]],
      dtype=[('summary', '<i8'), ('age', '<i8'), ('label', '<i8')])
>>> ahead['summary']
array([[0],
       [3],
       [6],
       [9]])

But be warned that those composite dtype arrays are not very useful as far as I can tell:

>>> ahead @ ahead.T
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid data type for einsum

to give just one example.

Comments

1

Create your own class with members including the numpy array and the headings as strings.

Comments

0

I think there is no way to do this. Try matrix.dtype. This should give you something like dtype('int32'). Your headers would be strings.

As far as I know you can only store one datatype in a numpy array/matrix.

2 Comments

a = np.asarray([2, 2.1, "2"], dtype = object) Now test the type of each element.
@MrT Good point. This way you could force the 0th element to be a string with the name.

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.