Alex16237
Alex16237

Reputation: 199

Merge duplicated indexes into one in pandas

I have a following dataframe

              value
index
a             w1
a             w2
a             w3
b             w1
b             w2
b             w3
c             w6
c             w6
c             w6

Is there any way to merge duplicated indexes into one while still preserving order of values?

              value
index
a             w1
              w2
              w3
b             w1
              w2
              w3 
c             w6
              w6
              w6

Is there any advantage to do so? It's more appealing visually and, as I understand, we store less of a data. But maybe there is a better way?

Upvotes: 1

Views: 125

Answers (1)

ansev
ansev

Reputation: 30920

You need to be able to locate each element by an index and unique column. Therefore you cannot do what you propose. The closest thing is a multiIndex:

new_df=df.groupby(level=0).apply(lambda x: x.reset_index(drop=True))
print(new_df)

        value
index        
a     0    w1
      1    w2
      2    w3
b     0    w1
      1    w2
      2    w3
c     0    w6
      1    w6
      2    w6

Upvotes: 1

Related Questions