I have a matrix where some rows' leading elements are NaNs (the number of leading NaNs may differ for each row). After the first non-NaN element, other elements in a row are guaranteed to be non-NaN as well.
Example:
A = np.array([[1,2,3],[np.nan,np.nan,1],[np.nan,1,2]])
I want to shift each row so that they align to the left by the first non-NaN element, like so:
B = np.array([[1,2,3],[1,np.nan,np.nan],[1,2,np.nan]])
Then I want to perform some operations (dependent on the relative index in the row), e.g.:
C = B*2
and then shift the rows back to align to the right once again:
D = np.array([[2,4,6],[np.nan,np.nan,2],[np.nan,2,4]])
I can think of a naive loopy solution that gets positions of the first non-NaN elements in each row and then performs shifts rowwise accordingly, but I suppose a more elegant (and probably much simpler) solution exists. I am willing to use either pandas or numpy to represent the data and their native methods/any 3rd party utilities to manipulate it. Execution time is also of no major concern.