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
197 views
in Technique[技术] by (71.8m points)

python - Converting Pandas Series to a List with indices preserved

I have this series:

ser = pd.Series(data=[11, 22, 33, 44, 88], index=[0, 1, 2, 3, 7])
ser
0    11
1    22
2    33
3    44
7    88

I want to convert it to a list so I do the following and result is:

ser.tolist()
result: [11, 22, 33, 44, 88]

However, what I want is a list where each element is inserted at the index it has in series:

[11, 22, 33, 44, 0, 0, 0, 88]

How can I achieve this?

question from:https://stackoverflow.com/questions/66056196/converting-pandas-series-to-a-list-with-indices-preserved

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

1 Answer

0 votes
by (71.8m points)

Try with reindex

ser.reindex(range(ser.index.max()+1),fill_value=0).tolist()
Out[13]: [11, 22, 33, 44, 0, 0, 0, 88]

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

...