Python 将数据帧轴折叠到单行
我有一个需要转换为单个数据帧行的元组列表,其中第一个元组项转换为列,第二个元组项转换为相应的值。以下是我尝试过的: 数据:Python 将数据帧轴折叠到单行,python,pandas,pivot,Python,Pandas,Pivot,我有一个需要转换为单个数据帧行的元组列表,其中第一个元组项转换为列,第二个元组项转换为相应的值。以下是我尝试过的: 数据: [(0, 0.52776772063535005), (4, 0.18798097301734626), (6, 0.09831844955142259), (5, 0.059519666448517437), (3, 0.054459995937603152), (9, 0.052905323520468818)] 将此数据视为test,我尝试将其转换为dat
[(0, 0.52776772063535005),
(4, 0.18798097301734626),
(6, 0.09831844955142259),
(5, 0.059519666448517437),
(3, 0.054459995937603152),
(9, 0.052905323520468818)]
将此数据视为test
,我尝试将其转换为dataframe,然后再转换为pivot,但无法将数据作为一个记录展平
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 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
或使用b填充
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
@幽会yw:-)快乐编码
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