Change Pandas Index Data Type to MultiIndex

I have a Pandas two-index dataframe

Column1 indexA indexB 1001 aaa 1 bbb 1 ccc 1 ddd 1 

created

 pd.read_sql(sql=sql, index_col=['indexA', 'indexB']) 

MySQL reads in indexB as unicode, and I would like to convert it to a string. My goal is to rotate the table and have entries in indexB - column names. When I do this with unicode values, I get the following column names:

                   

at startup

 pd.read_sql(sql=sql, index_col=['indexA', 'indexB']).unstack().fillna(0) 

EDIT: The comment suggested the following:

 df = pd.read_sql(sql) df['indexB'] = df['indexB'].astype(str) df = df.set_index(('indexA', 'indexB'), drop=True) 

which is nice to work with my problem (thanks). It would be nice to know if this can be done during initialization.

+5
source share
1 answer

the index can be reset before changing the type.

 df= df.reset_index() df['indexB'] = df['indexB'].astype(str) 
0
source

Source: https://habr.com/ru/post/1242135/


All Articles