How to use 'numpy add column to array' in Python

Every line of 'numpy add column to array' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
14def add_column_numpy_array(array, new_col):
15 placeholder = np.ones(array.shape[0])[:, np.newaxis]
16 result = np.hstack((array, placeholder))
17
18 if isinstance(new_col, np.ndarray):
19 assert array.shape[0] == new_col.shape[0], "input array row counts \
20 must be the same. \
21 Expected: {0}\
22 Actual: {1}".format(array.shape[0],
23 new_col.shape[0])
24 assert len(new_col.shape) <= 2, "new column must be 1D or 2D"
25
26 if len(new_col.shape) == 1:
27 new_col = new_col[:, np.newaxis]
28 return np.hstack((array, new_col))
29 elif isinstance(new_col, list):
30 assert len(new_col) == array.shape[0], "input array row counts \
31 must be the same. \
32 Expected: {0}\
33 Actual: {1}".format(len(array),
34 len(new_col))
35 new_col = np.array(new_col)
36 assert len(new_col.shape) == 1, "list elements cannot be iterable"
37 new_col = new_col[:, np.newaxis]
38 return np.hstack((array, new_col))
39 else:
40 placeholder = np.ones(array.shape[0])[:, np.newaxis]
41 result = np.hstack((array, placeholder))
42 result[:, -1] = new_col
43 return result

Related snippets