2

consider the below 2D numpy array

array1 = np.array([[ 0,  1,  2,  3,  4],
                   [ 5, 21, 15,  8, 12],
                   [ 2,  3,  4,  8,  3],
                   [ 3,  4,  5, 17, 41],
                   [ 4, 20,  7,  5,  6]])

my desired output is to shift the array at its diagonal to the left and pad the empty elements with np.nan

desired output

array([[ 0.,  1.,  2.,  3.,  4.],
       [21., 15.,  8., 12., nan],
       [4.,  8.,  3., nan, nan],
       [17., 41., nan, nan, nan],
       [6., nan, nan, nan, nan]])

how can i achieve this?

Siraj S.
  • 3,481
  • 3
  • 34
  • 48
  • Would it always have the same elements across all rows? – Divakar Jun 08 '19 at 05:45
  • No. the elements values across rows will vary – Siraj S. Jun 08 '19 at 05:45
  • Could you update with more representative sample data, i.e. different elements in different rows, so that people don't assume otherwise? – Divakar Jun 08 '19 at 05:46
  • 1
    Use Divakar's function like this: `strided_indexing_roll(array1, -np.arange(len(array1)))` – cs95 Jun 08 '19 at 05:47
  • I tried using @Divakar's strided function. But that solution is to roll rows starting from different index location for each row. it does not answer part of my question related to shifting to the left and padding empty elements to the right with np.nan – Siraj S. Jun 08 '19 at 08:24
  • @SirajS. Isn't that strided one giving you the expected output? – Divakar Jun 08 '19 at 08:31
  • @Divakar. the function here (https://stackoverflow.com/questions/20360675/roll-rows-of-a-matrix-independently) rolls the rows independently but starts with first element, i want the diagonal element to shift to the left. – Siraj S. Jun 08 '19 at 09:44
  • @SirajS. I understand what you want. On that doesn't https://stackoverflow.com/a/51614167/ work with `strided_indexing_roll(array1, -np.arange(len(array1)))` giving you what you want? – Divakar Jun 08 '19 at 09:47
  • @Divakar, yes. this works perfect. thank you. – Siraj S. Jun 08 '19 at 09:51

0 Answers0