也许这已经得到了回答,但我很难找到问题。假设我在文件中有以下数据:
date, id, int1, int2, int3
02/03/2015, 2, 23, 65, 99
10/06/2016, 4, 84, 12, 35
10/01/2017, 6, 53, 6, 78
我可以快速编写一个numpy代码段:
import StringIO
import numpy as np
hdr = 'date, id, int1, int2, int3'
date = '''
02/03/2015, 2, 23, 65, 99
10/06/2016, 4, 84, 12, 35
10/01/2017, 6, 53, 6, 78
'''
lines = '%s%s' % (hdr, date)
pseudo_file = StringIO.StringIO(lines)
np_dtypes = 'S10,%s' % ','.join(['i4' for x in hdr.split(',')[1:]])
np1 = np.genfromtxt(pseudo_file, delimiter=',', names=True, dtype=np_dtypes)
print np1
print np1.dtype.names
print np1.shape
print np1['date']
print np1['int3']
这将给我以下输出:
[('02/03/2015', 2, 23, 65, 99) ('10/06/2016', 4, 84, 12, 35)
('10/01/2017', 6, 53, 6, 78)]
('date', 'id', 'int1', 'int2', 'int3')
(3L,)
['02/03/2015' '10/06/2016' '10/01/2017']
[99 35 78]
可以看到numpy能够成功解析数组。但是,如何将其分为两部分:
拆分应该以保持每列的名称结构的方式完成。
答案 0 :(得分:0)
您还没有用np1['date']
拆分字符串吗?要保留其列名称,您可以将'日期'列表中的列名称(感谢@hpaulj):
dates=np1[['date']]
dates
#array([('02/03/2015',), ('10/06/2016',), ('10/01/2017',)],
# dtype=[('date', 'S10')])
获得整理:
ints=np1[['int1','int2','int3']]
ints
#array([(23, 65, 99), (84, 12, 35), (53, 6, 78)],
# dtype=[('int1', '<i4'), ('int2', '<i4'), ('int3', '<i4')])