![]() |
numpy adding columns - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: numpy adding columns (/thread-34974.html) |
numpy adding columns - rwahdan - Sep-21-2021 Hi, I am trying to add columns to a numpy array but i am getting an error import numpy as np numbers = np.array([ [2,4], [8,10], [50,100] ]) add = numbers[:,0] + numbers[:,1] mul = numbers[:,0] * numbers[:,1] numbers = np.hstack((numbers,add)) numbers = np.hstack((numbers,mul))i am getting this error:
RE: numpy adding columns - jefsummers - Sep-21-2021 Not sure if this is what you are looking for, but here goes import numpy as np numbers = np.array([ [2,4], [8,10], [50,100] ]) add = numbers[:,0] + numbers[:,1] mul = numbers[:,0] * numbers[:,1] print(numbers) print(add.transpose()) numbers = np.append(numbers,add.transpose()) numbers = np.append(numbers,mul.transpose()) print(numbers)
RE: numpy adding columns - rwahdan - Sep-21-2021 (Sep-21-2021, 03:56 PM)jefsummers Wrote: Not sure if this is what you are looking for, but here goes Thanks for the reply. What I am looking for is to add the 2 new arrays (add, mul) as columns so the answer should be (columns):
RE: numpy adding columns - rwahdan - Sep-21-2021 I just a solution but if anyone can think of a better way please share... import numpy as np numbers = np.array([ [2,4], [8,10], [50,100] ]) add = numbers[:,0] + numbers[:,1] add = add.reshape(3,1) mul = numbers[:,0] * numbers[:,1] mul = mul.reshape(3,1) numbers_add = np.hstack((numbers, add)) numbers_mul = np.hstack((numbers_add, mul)) print(numbers_mul)the results:
RE: numpy adding columns - deanhystad - Sep-21-2021 import numpy as np numbers = np.array([[2,4], [8,10], [50,100]]) table = np.c_[numbers, np.sum(numbers, axis=1), np.prod(numbers, axis=1)] print(' A B + *', table, sep='\n')
|