本文介绍了如何将索引转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的索引:
Index([u'Newal', u'Saraswati Khera', u'Tohana'], dtype='object')
我必须将此格式转换为以下格式的列表:
I have to convert this format into list with following format:
['Newal','SaraswatiKhera','Tohana']
推荐答案
您可以使用 tolist
或list
:
print df.index.tolist()
print list(df.index)
但是最快的解决方案是通过 values
tolist
(感谢 EdChum )
But the fastest solution is convert np.arry
by values
tolist
(thanks EdChum)
print df.index.values.tolist()
示例:
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
:
print [x.encode('UTF8') for x in idx.tolist()]
['Newal', 'Saraswati Khera', 'Tohana']
另一种解决方案:
print [str(x) for x in idx.tolist()]
['Newal', 'Saraswati Khera', 'Tohana']
,但是如果unicode字符串字符不在ASCII范围内,则会失败.
but it would fail if the unicode string characters do not lie in the ascii range.
时间:
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
这篇关于如何将索引转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!