Skip to content Skip to sidebar Skip to footer

Resetting Index Based On List

I want to reset the index based on a list Lets say i have dataframe like this list = ['RGB','RBR','RGD'] a b RBR 0 1 RGD 10 2 RGB 11 3 RGD 10 2 R

Solution 1:

Do not reindex just use .loc i.e

li =  ['RGB','RBR','RGD']
df = df.loc[li]

    a  b
RGB  11  3
RGB  11  3
RBR   0  1
RBR   0  1
RGD  10  2
RGD  10  2
RGD  10  2
RGD  10  2

Solution 2:

You have duplicate values in your index. pd.DataFrame.reindex requires your index to be unique.

One efficient solution available to Pandas is Categorical Data, taking care to specify ordered=True.

L = ['RGB', 'RBR', 'RGD']

df.index = pd.Categorical(df.index, categories=L, ordered=True)

res = df.sort_index()

print(res)

      a  b
RGB  113
RGB  113
RBR   01
RBR   01
RGD  102
RGD  102
RGD  102
RGD  102

Post a Comment for "Resetting Index Based On List"