简体   繁体   中英

Reshape pandas dataframe from column to unique index

I'm trying to reshape my dataframe, in which I want the Person to the be index, however how do I make it so the index is unique? I don't know want duplicates in my Index.

df = pd.DataFrame({'Person':['Paul','Paul','Paul','John','John','Mia'],'Score':[24,23,54,64,89,56],'Type':['A','C','F','A','G','X'],'Number':[1,2,3,1,2,1]})

df.set_index('Person',inplace = True)

Desired output:

在此处输入图像描述

If you just wanna remove the duplicate values from the index use:

df = df.set_index('Person')
df.index = np.where(df.index.duplicated(), '', df.index) 

You could create a MultiIndex , keeping the previous numerical index as the second level:

df.set_index(['Person', df.index], inplace=True)
df
            Score   Type    Number
Person              
Paul    0   24      A       1
        1   23      C       2
        2   54      F       3
John    3   64      A       1
        4   89      G       2
Mia     5   56      X       1

I think this is the closest you can get to your desired output, because by definition there has to be an index value for each row of the dataframe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM