iterating a numpy matrix, and assign its rows with information from other dataframe and numpy array

Viewed 84

I have a matrix, e.g., defined as x_matrix = np.zeros(200,16) Iterating over the rows, I need to assign each row of this matrix with two component vectors, a1 is an array with 10 elements, a2 is a corresponding row belonging to a pandas dataframe y_dataframe y_dataframe has shape of (200,6)

I can iterate the matrix as follows. But I also need the row number of x_matrix to retreive the corresponding row in the y_dataframe. Are there other ways to iterate the matrix rows, and compose its rows with different component vectors described as above.

for row in x_matrix
1 Answers

You can do this without iteration if you wish using np.repeat and np.hstack:

# assuming `a1` is shaped (10,) i.e. 1D array
a1_repeated = np.repeat(a1[np.newaxis, :], 200, axis=0)

x_matrix = np.hstack((a1_repeated, y_dataframe))

where we first convert a1 into a row vector of shape (10, 1) via [np.new_axis, :], then repeat it 200 times row-wise (axis=0). Lastly we horizontally stack this (200, 10) shaped a1_repeated and y_dataframe to get an array of shape (200, 16).

But if you want to iterate, enumerate gives you index you are at:

for row_number, row in enumerate(x_matrix):
    x_matrix[row_number] = [*a1, *y_dataframe.iloc[row_number]]

where y_dataframe.iloc[row_number] is equal to a2 you mention i.e. a row of dataframe.

Related