我有一个元组列表,我需要将其转换为单个数据帧行,其中第一个元组项转换为列,第二个元组转换为相应的值。这就是我的尝试:
数据:
[(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
有没有办法可以将数据线折叠成一行,而不是将数据放在多个索引上?
答案 0 :(得分:3)
您可以将索引更改为单个值
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
或者我们从数据
创建你的dfpd.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
答案 1 :(得分:1)
您也可以将索引设置为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