Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert categorical index to normal index

I have the following DataFrame (result of the method unstack):

df = pd.DataFrame(np.arange(12).reshape(2, -1),
                  columns=pd.CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c']))

df looks like this:

   a  b  c  a   b   c
0  0  1  2  3   4   5
1  6  7  8  9  10  11

When I try to df.reset_index() I get the following error:

TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category

To bypass this problem I want to convert the column's index from categorical to a normal one. What is the most straightforward way to do it? Maybe you have an idea of how to reset the index without index conversion. I have the following idea:

df.columns = list(df.columns)
like image 358
Mykola Zotko Avatar asked Feb 13 '20 08:02

Mykola Zotko


1 Answers

Most general is converting columns to list:

df.columns = df.columns.tolist()

Or if possible, convert them to strings:

df.columns = df.columns.astype(str)
df = df.reset_index()
print (df)

   index  a  b  c  a   b   c
0      0  0  1  2  3   4   5
1      1  6  7  8  9  10  11
like image 130
jezrael Avatar answered Oct 12 '22 12:10

jezrael