Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shift numpy array column and row?

Tags:

python

numpy

row

I have numpy array like this, where I have one column and one row of ZEROS :

 ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. ],
   [3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
   [3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
   [2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9],
   [1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8],
   [0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]])

I want to shift the zero-row to the top and the zero-column either to the left or remove it :

 ([[0. , 0. , 0. , 0. , 0. , 0. ]
   [0. , 2.8, 3.5, 2.5, 1. , 0.8],
   [3.5, 2.5, 0. , 2.8, 1.3, 1.1],
   [3.6, 3.8, 3.3, 2.5, 0.6, 0.4],
   [2.5, 1.5, 2.8, 0. , 3.1, 1.9],
   [1. , 0.8, 1.3, 3.1, 0. , 2.8],
   [0.8, 1.6, 1.1, 1.9, 2.8, 0. ]])

any quick and easy way to do it ? BTW I know the col&row-number, so i doesnt have to search for it.

like image 647
sten Avatar asked Mar 10 '26 11:03

sten


1 Answers

Delete both the column and row and add back in a row of zeros.

This works for your example:

import numpy as np
a =  np.array([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. ],
   [3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
   [3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
   [2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9],
   [1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8],
   [0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]])

def remove_column_of_zeros_and_shift_row(a, row, col):
    without_row = np.delete(a, row, axis=0)
    without_row_and_col = np.delete(without_row, col, axis=1)
    z = np.zeros((1, len(without_row_and_col[0])))
    without_col_shifted_row = np.append(z, without_row_and_col, axis=0)
    return without_col_shifted_row

my_result = remove_column_of_zeros_and_shift_row(a, 1, 3)
like image 73
Zev Avatar answered Mar 13 '26 00:03

Zev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!