JamesHudson81
JamesHudson81

Reputation: 2273

How can I split index into two columns?

I have the following df:

                           0
0Basic Materials        0.561830
1Financial              0.337054
2Consumer Cyclical      0.017414
3Financial              0.073028
4Consumer Non-cyclical  0.010673

I would like to split the index column in order to obtain the following output:

           0                   1
0    Basic Materials        0.561830
1    Financial              0.337054
2    Consumer Cyclical      0.017414
3    Financial              0.073028
4    Consumer Non-cyclical  0.010673

The only methodology I know in order to split columns is using rsplit , however dont know how could I apply it in this case.

Upvotes: 0

Views: 897

Answers (1)

jezrael
jezrael

Reputation: 862731

If want extract numeric values first convert indices to to_series, then join to original and set_index:

df = (df.index.to_series().str.extract('(?P<a>\d+)(?P<b>.*)', expand=True)
       .join(df)
       .set_index('a'))
#if need default columns names
df.columns = range(len(df.columns))
print (df)
                       0         1
a                                 
0        Basic Materials  0.561830
1              Financial  0.337054
2      Consumer Cyclical  0.017414
3              Financial  0.073028
4  Consumer Non-cyclical  0.010673

Upvotes: 0

Related Questions