我有一个元组列表,我需要将其转换为单个数据框行,其中第一个元组项目被转换为列,第二个元组转换为相应的值。这是我尝试的:
数据:
[(0, 0.52776772063535005),
(4, 0.18798097301734626),
(6, 0.09831844955142259),
(5, 0.059519666448517437),
(3, 0.054459995937603152),
(9, 0.052905323520468818)]
将这些数据视为test
,我尝试将其转换为数据框架,然后转换为枢轴,但我无法将数据作为一个记录变平。
test = pd.DataFrame.from_records(scores[0])
test.columns=['t1','t2']
t1 t2
0 0 0.527768
1 4 0.187981
2 6 0.098318
3 5 0.059520
4 3 0.054460
5 9 0.052905
test2 = test.pivot(index=None, columns='t1',values='t2')
t1 0 3 4 5 6 9
0 0.527768 NaN NaN NaN NaN NaN
1 NaN NaN 0.187981 NaN NaN NaN
2 NaN NaN NaN NaN 0.098318 NaN
3 NaN NaN NaN 0.05952 NaN NaN
4 NaN 0.05446 NaN NaN NaN NaN
5 NaN NaN NaN NaN NaN 0.052905
我想要的是一排:
t1 0 3 4 5 6 9
0 0.527768 0.05446 0.187981 0.05952 0.098318 0.052905
有没有办法将枢轴折叠成一排,而不是在多个索引上使用我的数据?
您可以将索引更改为一个单个值
test.index=[0]*len(test)
test.pivot(index=None, columns='t1',values='t2')
Out[525]:
t1 0 3 4 5 6 9
0 0.527768 0.05446 0.187981 0.05952 0.098318 0.052905
或使用bfill
test.pivot(index=None, columns='t1',values='t2').bfill().iloc[[0],:]
Out[532]:
t1 0 3 4 5 6 9
0 0.527768 0.05446 0.187981 0.05952 0.098318 0.052905
或我们从数据创建您的DF
pd.Series(dict(data)).to_frame().T
Out[555]:
0 3 4 5 6 9
0 0.527768 0.05446 0.187981 0.05952 0.098318 0.052905
您可以将索引设置为 t1
,并且在显示时,将数据框架转换时,如果需要,可以选择通过索引对值进行排序。这样,就不必枢转值。
import pandas as pd
records = [
(0, 0.52776772063535005),
(4, 0.18798097301734626),
(6, 0.09831844955142259),
(5, 0.059519666448517437),
(3, 0.054459995937603152),
(9, 0.052905323520468818)
]
test = pd.DataFrame.from_records(records, columns=['t1', 't2'])
test = test.set_index('t1')
test = test.sort_index().transpose()
# prints out:
t1 0 3 4 5 6 9
t2 0.527768 0.05446 0.187981 0.05952 0.098318 0.052905