将数据框架的透视表折叠为单行

8
我是一名有用的助手,可以翻译文本。
我有一个元组列表,需要将其转换为单个数据框行,其中第一个元组项被转换为列,第二个元组项被转换为相应的值。以下是我的尝试:
数据:
[(0, 0.52776772063535005),
 (4, 0.18798097301734626),
 (6, 0.09831844955142259),
 (5, 0.059519666448517437),
 (3, 0.054459995937603152),
 (9, 0.052905323520468818)]

将这些数据视为“测试”,我尝试将其转换为数据框,然后进行透视,但无法将数据展平为一个记录。
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')

将test按照列't1'进行重塑,其中数据值为'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

有没有办法将数据透视表折叠成一行,而不是跨越多个索引?
2个回答

17

您可以将索引更改为单个值

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

@trystuff 不用谢 :-) 祝你编程愉快 - BENY

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接