在Datafram中只在索引上显示一次重复字符串

2024-05-16 12:50:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧

import pandas as pd

df=pd.DataFrame({
'Foo': ['John','John','John','Steve','Steve','Ted'],
'Score': [4.1,6,5,7,6,0],
'Picotee':[0,1,0,1,0,0]
})

df = df.set_index('Foo', append=True)

print(df)

打印到:

>>> 
         Picotee  Score
 Foo                  
John         0    4.1
John         1    6.0
John         0    5.0
Steve        1    7.0
Steve        0    6.0
Ted          0    0.0

有没有可能让输出在索引列“Foo”中只显示一次重复的条目

>>> 
         Picotee  Score
 Foo                  
John         0    4.1
             1    6.0
             0    5.0
Steve        1    7.0
             0    6.0
Ted          0    0.0

Tags: 数据importdataframepandasdfindexfooas
1条回答
网友
1楼 · 发布于 2024-05-16 12:50:06

根据您的评论,您不需要这一行:df = df.set_index('Foo', append=True)所以您可以去掉它并使用简单的pivot_table

pd.pivot_table(df, index=['Foo', 'Score'])

输出:

                Picotee
Foo     Score   
John    4.1     0
        5.0     0
        6.0     1
Steve   6.0     0
        7.0     1
Ted     0.0     0

相关问题 更多 >