Home > Back-end >  Adding a column in a Numpy array using values existing in the Array
Adding a column in a Numpy array using values existing in the Array

Time:02-02

ive been attempting to add a column to my Array that is a product of values from the same row this example is calculating bmi's and adding them

example matrix [weight, height]

100 1.5
130 1.6

example matrix of what im trying to acheive [weight, height, BMI] with BMI = weight / height^2

100 1.5 44.4
130 1.6 50.8

ive no idea where to start as im not very proficient with python and numpy. ive been trying to create a separate array and then appending that, but ive had no luck there as ive been unable to produce an array of the values i need.

the best attempt i had at doing that is

fbmi = []
fweights = female[:,0]
fheights = (female[:,:1]/100)

for i in range(len(fweights)):
    fbmi.append(np.round(fweights[i]/(fheights[i]**2),2))
print(fbmi)

which gives a result looking like: [array([102.99]), array([109.77]), array([136.99]) ... , array([127.23]), array([120.77])]

numpy has been called in an earlier step on the notebook female[] is a numpy array holding

CodePudding user response:

The hstack method can add a column to at existing array. Note that we have to reshape the row of results into a column first:

import numpy as np

x = [[100,1.5],[130,1.6]]
x = np.array(x)
z = (x[:,0]/(x[:,1]*x[:,1])).reshape(-1,1)
x = np.hstack((x,z))
print(x)

Output:

[[100.           1.5         44.44444444]
 [130.           1.6         50.78125   ]]

CodePudding user response:

Use simple column slicing and np.c_ to concatenate the new column:

a = np.array([[100, 1.5],
              [130, 1.6]])

a = np.c_[a, a[:, 0] / a[:, 1]**2]

Output:

array([[100.  ,   1.5 ,  44.44],
       [130.  ,   1.6 ,  50.78]])
  • Related