将元组列表转换为 DataFrame(第一个参数:列,第二个参数:值)

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

所以我需要一个来自 list_of_list_of_tuples:

的 DataFrame

我的数据是这样的:

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

我需要的是这个:

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

所以元组中的第一个参数是列,第二个是值。 索引也很好。 谁能帮我? 我不知道如何制定代码。

将每个元组转换为字典,传递给 DataFrame 构造函数并最后添加 DataFrame.reindex 以更改顺序并添加缺失的列:

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
tuples = [[(5,0.45),(6,0.56)],[(1,0.23),(2,0.54),(6,0.63)],[(3,0.86),(6,0.36)]]

for x in tuples:
    print(x)
    index=[]
    values=[]
    for tuple in x:
        print(tuple[0],tuple[1])
        index.append(tuple[0])
        values.append(tuple[1])
    print(index,values)