python - 关于NumPy数组操作的问题
ringa_lee
ringa_lee 2017-06-30 09:56:09
0
3
1336
['000001_2017-03-17.csv', '000001_2017-03-20.csv',
 '000002_2017-03-21.csv', '000002_2017-03-22.csv',
 '000003_2017-03-23.csv', '000004_2017-03-24.csv']

numpy数组,总共有几个万个元素。现在想保留每个元素前面的编号000001之类的,并且去掉重复,只保留唯一的一个编号。结果应该是['000001','000002','000003','000004']
除了用for语句实现外,有没有更高效的办法?

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
迷茫

写个NumPy的吧~

python3

>>> import numpy as np
>>> a = np.array(['000001_2017-03-17.csv', '000001_2017-03-20.csv',
 '000002_2017-03-21.csv', '000002_2017-03-22.csv',
 '000003_2017-03-23.csv', '000004_2017-03-24.csv'])

>>> b = np.unique(np.fromiter(map(lambda x:x.split('_')[0],a),'|S6'))
>>> b
array([b'000001', b'000002', b'000003', b'000004'], 
      dtype='|S6')

还可以这样写:np.frompyfunc
'|S6'是以6个字节存储字符串

'<U6'是以6个小端序Unicode字符存储字符串

>>> b = np.array(np.unique(np.frompyfunc(lambda x:x[:6],1,1)(a)),dtype='<U6')
>>> b
array(['000001', '000002', '000003', '000004'], 
      dtype='<U6')
学习ing

综合两位仁兄的写法
@同意并接受 @xiaojieluoff

如果编号长度固定是前六位,最快的写法下面第一种最快

import time
lst = ['000001_2017-03-17.csv', '000001_2017-03-20.csv', '000002_2017-03-21.csv', '000002_2017-03-22.csv', '000003_2017-03-23.csv', '000004_2017-03-24.csv'] * 1000000

start = time.time()
data = {_[:6] for _ in lst}
print 'dic: {}'.format(time.time() - start)

start = time.time()
data = set(_[:6] for _ in lst)
print 'set: {}'.format(time.time() - start)

start = time.time()
data = set(map(lambda _: _[:6], lst))
print('map:{}'.format(time.time() - start))

start = time.time()
data = set()
[data.add(_[:6]) for _ in lst]
print('for:{}'.format(time.time() - start))

耗时:
dic: 0.72798705101
set: 0.929664850235
map:1.89214396477
for:1.76194214821
某草草

使用 map 和匿名函数

lists = ['000001_2017-03-17.csv', '000001_2017-03-20.csv','000002_2017-03-21.csv','000002_2017-03-22.csv','000003_2017-03-23.csv', '000004_2017-03-24.csv']

data = list(set(map(lambda x:x.split('_')[0], lists)))

print(data)

输出:

['000003', '000004', '000001', '000002']

运行下面代码可以看到 , 在 6百万 条数据下,map 比 for 快了 0.6s 左右

import time


lists = ['000001_2017-03-17.csv', '000001_2017-03-20.csv', '000002_2017-03-21.csv', '000002_2017-03-22.csv', '000003_2017-03-23.csv', '000004_2017-03-24.csv'] * 1000000

map_start = time.clock()

map_data = list(set(map(lambda x:x.split('_')[0], lists)))


map_end = (time.clock() - map_start)

print('map 运行时间:{}'.format(map_end))


for_start = time.clock()

data = set()
for k in lists:
    data.add(k.split('_')[0])

for_end = (time.clock() - for_start)
print('for 运行时间:{}'.format(for_end))

输出:

map 运行时间:2.36173
for 运行时间:2.9405870000000003

如果把测试数据扩大到 6千万, 差距就更明显了

map 运行时间:29.620203
for 运行时间:33.132621
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板