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?

2
  • 2
    Have you tried writing a function to pad with zeros? Commented Jan 30, 2018 at 15:44
  • From the Help center: Check the spelling of your question carefully. Commented Jan 30, 2018 at 15:45

3 Answers 3

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]]
Sign up to request clarification or add additional context in comments.

Comments

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]]

3 Comments

This looks interesting. It would be great if you can add some more details how this works
@GarbageCollector using constructor creat data frame, sort each row by using NaN or not (If NaN move to the front), then convert back to list
@GarbageCollector its simple sorting of row elements using the key.
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]]

1 Comment

Maybe add astype( int ) :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.