Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...