Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - How to fill multiple list by 0's in Pandas data frame?

I have Pandas data frame and I am trying to add 0's in those lists where numbers are missing. In the below data frame, the max length of the list is 4 which is in the 3rd position. accordingly, I will add 0's to the remaining lists.

Input:

        Lists
0     [158, 202]
1     [609, 405]
2     [544, 20]
3     [90, 346, 130, 202]
4     [6]

Output:

        Lists
0     [158, 202, 0, 0]
1     [609, 405, 0, 0]
2     [544, 20, 0, 0]
3     [90, 346, 130, 202]
4     [6, 0, 0, 0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another way to do this would be using apply with a lambda function -

maxlen = df['Lists'].str.len().max() #as suggested by Anky, better than an apply since vectorised
f = lambda x: x + ([0] * (maxlen - len(x)))

df['Padded'] = df['Lists'].apply(f)
print(df)
                 Lists               Padded
0           [158, 202]     [158, 202, 0, 0]
1           [609, 405]     [609, 405, 0, 0]
2            [544, 20]      [544, 20, 0, 0]
3  [90, 346, 130, 202]  [90, 346, 130, 202]
4                  [6]         [6, 0, 0, 0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...