快速制作带字母表的索引前缀

时间:2017-01-25 07:51:14

标签: pandas

是否有快速方法从a1..a111制作索引?现在只有1..111。

   fruit = pd.Series(['aa'] * 50 + ['bb'] * 50 + [None] * 10, name='fruit', index=range(1,111))

2 个答案:

答案 0 :(得分:4)

使用rename_axis

fruit.rename_axis('a{}'.format)

a1        aa
a2        aa
a3        aa
a4        aa
a5        aa
a6        aa
a7        aa
a8        aa
a9        aa
a10       aa
a11       aa
a12       aa

答案 1 :(得分:2)

您可以使用list comprehension

fruit = pd.Series(['aa'] * 50 + ['bb'] * 50 + [None] * 10, name='fruit',
                  index=['a'+ str(i) for i in range(1,111)])

print (fruit)
a1        aa
a2        aa
a3        aa
a4        aa
a5        aa
a6        aa
a7        aa
a8        aa
a9        aa
...
...

另一种更快的解决方案是将index值转换为string并添加a

fruit = pd.Series(['aa'] * 50 + ['bb'] * 50 + [None] * 10, name='fruit', index=range(1,111))
fruit.index = 'a' + fruit.index.astype(str)

<强>计时

In [86]: %timeit pd.Series(['aa'] * 50000 + ['bb'] * 50000 + [None] * 10000, name='fruit', index=['a'+ str(i) for i in range(1,110001)])
10 loops, best of 3: 76 ms per loop

In [87]: %timeit pd.Series(['aa'] * 50000 + ['bb'] * 50000 + [None] * 10000, name='fruit', index=range(1,110001)).rename_axis('a{}'.format)
10 loops, best of 3: 84.9 ms per loop

In [88]: %timeit jez()
10 loops, best of 3: 46.5 ms per loop