Python Forum
Add column to numpy matrix
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add column to numpy matrix
#1
Dear all,
I am trying to add a column to a numpy matrix. I can make a running example as follows:

import numpy as np
X = np.random.uniform(size=(10,3))
X.shape
Out[3]: (10, 3)
n,m = X.shape
X0 = np.ones((n,1))
X0.shape
Out[6]: (10, 1)
Xnew = np.hstack((X,X0))
Xnew.shape
Out[8]: (10, 4)
The data I got comes from a Pandas dataframe which I converted to numpy with .to_numpy, but then:

import pandas as pd
df =  pd.read_csv("Data.tsv", delimiter='\t')
X = df[['mr', 'fcn', 'weight']]
x = X.to_numpy()
S = df[['serial']]
sa = S.to_numpy() 
s = sa.ravel()
x.shape 
Out[14]: (15744, 3)
s.shape 
Out[15]: (15744,)
z =  np.hstack((x, s))
Traceback (most recent call last):

  File "<ipython-input-16-c88a113c6e49>", line 1, in <module>
    z =  np.hstack((x, s))

  File "/home/gigiux/.local/lib/python3.6/site-packages/numpy/core/shape_base.py", line 340, in hstack
    return _nx.concatenate(arrs, 1)

ValueError: all the input arrays must have same number of dimensions
This is also the case for stack, vstack, concatenate(axis=0,1,2). Nevertheless, all these objects are numpy arrays:

type(X)
Out[6]: numpy.ndarray
type(X0)
Out[7]: numpy.ndarray
type(Xnew)
Out[8]: numpy.ndarray
type(x)
Out[2]: numpy.ndarray
type(s)
Out[4]: numpy.ndarray
What am I missing? Why X0 has two dimensions (10, 1) but s has only one (15744)? Is that the problem?
Thank you
Reply
#2
(Aug-01-2019, 07:53 AM)Gigux Wrote: Is that the problem?
Yes. You could be able to append array with shape (15744, 1);

This should work:

np.hstack((x, s[:, np.newaxis]))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 300 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,530 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  convert 'A B C' to numpy float matrix rezabma 4 2,491 Feb-27-2020, 09:48 AM
Last Post: rezabma
  Python/C API Matrix to Numpy jibarra 0 1,854 Jul-29-2019, 03:25 PM
Last Post: jibarra
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 2,934 Apr-09-2019, 04:54 PM
Last Post: PhysChem
  counting the occurence of a specified number in a numpy-matrix PhysChem 1 2,387 Apr-03-2019, 01:37 PM
Last Post: PhysChem
  NumPy array; selecting the a single column econmajor 0 3,032 Oct-24-2017, 04:25 PM
Last Post: econmajor

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020