关于python:如何将Index转换成列表?

how to convert Index into list?

本问题已经有最佳答案,请猛点这里访问。

我的索引:

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

我必须将此格式转换为以下格式的列表:

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

您可以使用tolistlist

1
2
3
print df.index.tolist()

print list(df.index)

但最快的解决方案是用valuestolist转换np.arry(谢谢edchum)

1
print df.index.values.tolist()

Sample:

1
2
3
4
5
6
7
8
9
10
11
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']

如果需要编码UTF-8

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

另一个解决方案:

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

但如果Unicode字符串字符不在ASCII范围内,它将失败。

计时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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']

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


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

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

In [92]: %timeit df.index.values.tolist()
The slowest run took 62.72 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 787 ns per loop