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

pandas - Converting a list of list of tuples to a DataFrame (First argument: column, Second argument: value)

So I need a DataFrame out of a list_of_list_of_tuples:

My data looks like this:

tuples = [[(5,0.45),(6,0.56)],[(1,0.23),(2,0.54),(6,0.63)],[(3,0.86),(6,0.36)]]

What I need is this:

index 1 2 3 4 5 6
1 nan nan nan nan 0.45 0.56
2 0.23 0.54 nan nan nan 0.63
3 nan nan 0.86 nan nan 0.36
question from:https://stackoverflow.com/questions/65919745/converting-a-list-of-list-of-tuples-to-a-dataframe-first-argument-column-seco

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

1 Answer

0 votes
by (71.8m points)

Convert each tuple to dictionary, pass to DataFrame constructor and last add DataFrame.reindex for change order and also add missing columns:

df = pd.DataFrame([dict(x) for x in tuples])

df = df.reindex(range(df.columns.min(), df.columns.max() + 1), axis=1)
print (df)
      1     2     3   4     5     6
0   NaN   NaN   NaN NaN  0.45  0.56
1  0.23  0.54   NaN NaN   NaN  0.63
2   NaN   NaN  0.86 NaN   NaN  0.36

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

...