1

So I found this: Numpy: Fix array with rows of different lengths by filling the empty elements with zeros

But what I actually want is this:

mylist = [[1],[1,2],[1,2,3]]

mylist.fill()
>>> [[0,0,1], [0,1,2], [1,2,3]]

I know that pandas' fillna fills but the 0 are at the right part of my matrix and I need them at the left part. Any clues?

Guillem
  • 144
  • 4
  • 13

3 Answers3

4

I think this should do it:

def fill(a):
    length = max([len(i) for i in a])
    return [[0]*(length-len(i)) + i for i in a]

fill(mylist)
#[[0,0,1], [0,1,2], [1,2,3]]
zipa
  • 27,316
  • 6
  • 40
  • 58
2

Since you tag pandas

pd.DataFrame(mylist).\
  apply(lambda x: sorted(x, key=pd.notnull), 1).\
    fillna(0).astype(int).values.tolist()
Out[89]: [[0, 0, 1], [0, 1, 2], [1, 2, 3]]
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Fillna with 0 and sort values check if they are not 0's i.e

df = pd.DataFrame(mylist)
df.fillna(0).apply(lambda x : sorted(x,key=lambda x : x!=0),1).values.astype(int).tolist()

[[0, 0, 1], [0, 1, 2], [1, 2, 3]]
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108