Sai Rajesh Sai Rajesh - 6 months ago 26
Python Question

how to convert Index into list?

My index:

Index([u'Newal', u'Saraswati Khera', u'Tohana'], dtype='object')


I have to convert this format into list with following format:

['Newal','SaraswatiKhera','Tohana']

Answer

You can use tolist or list:

print df.index.tolist()

print list(df.index)

Sample:

import pandas as pd

idx = pd.Index([u'Newal', u'Saraswati Khera', u'Tohana'])
print idx
Index([u'Newal', u'Saraswati Khera', u'Tohana'], dtype='object')

print idx.tolist()
[u'Newal', u'Saraswati Khera', u'Tohana']

print list(idx)
[u'Newal', u'Saraswati Khera', u'Tohana']

If you need encode UTF-8:

print [x.encode('UTF8') for x in idx.tolist()]
['Newal', 'Saraswati Khera', 'Tohana']

Another solution:

print [str(x) for x in idx.tolist()]
['Newal', 'Saraswati Khera', 'Tohana']

but it would fail if the unicode string characters do not lie in the ascii range.

Timings:

import pandas as pd
import numpy as np

#random dataframe
np.random.seed(1)
df = pd.DataFrame(np.random.randint(10, size=(3,3)))
df.columns = list('ABC')
df.index = [u'Newal', u'Saraswati Khera', u'Tohana']
print df

print df.index
Index([u'Newal', u'Saraswati Khera', u'Tohana'], dtype='object')

print df.index.tolist()
[u'Newal', u'Saraswati Khera', u'Tohana']

print list(df.index)
[u'Newal', u'Saraswati Khera', u'Tohana']


In [50]: %timeit list(df.index)
The slowest run took 27.97 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 2.16 µs per loop

In [51]: %timeit df.index.tolist()
The slowest run took 28.88 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 1.72 µs per loop
Comments