Numpy genfromtxt迭代列

时间:2015-08-27 17:40:13

标签: python numpy genfromtxt

我正在使用NumPy' genfromtext从CSV文件中获取列。

需要拆分每一列并将其分配到单独的SQLAlchemy SystemRecord以及其他一些列和属性,并添加到数据库中。

最好的做法是将列f1迭代到f9并将它们添加到会话对象中吗?

到目前为止,我使用了以下代码,但我不想为每个f列执行相同的操作:

t = np.genfromtxt(FILE_NAME,dtype=[(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20), (np.str_, 20), (np.str_, 20),(np.str_, 20)]\
 ,delimiter=',',filling_values="None", skiprows=0,usecols=(0,1,2,3,4,5,6,7,8,9,10))

for r in enumerate(t):
    _acol = r['f1'].split('-')
    _bcol = r['f2'].split('-')
    ....
    arec = t_SystemRecords(first=_acol[0], second=_acol[1], third=_acol[2], ... )
    db.session.add(arec)
    db.session.commit()

1 个答案:

答案 0 :(得分:2)

看看t.dtype。或r.dtype

制作一个样本结构化数组(genfromtxt返回的内容):

t = np.ones((5,), dtype='i4,i4,f8,S3')

看起来像:

array([(1, 1, 1.0, b'1'), (1, 1, 1.0, b'1'), (1, 1, 1.0, b'1'),
       (1, 1, 1.0, b'1'), (1, 1, 1.0, b'1')], 
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<f8'), ('f3', 'S3')])

dtypedtype.names是:

In [135]: t.dtype
Out[135]: dtype([('f0', '<i4'), ('f1', '<i4'), ('f2', '<f8'), ('f3', 'S3')])

In [138]: t.dtype.names
Out[138]: ('f0', 'f1', 'f2', 'f3')

遍历名称以查看各列:

In [139]: for n in t.dtype.names:
   .....:     print(t[n])
   .....:     
[1 1 1 1 1]
[1 1 1 1 1]
[ 1.  1.  1.  1.  1.]
[b'1' b'1' b'1' b'1' b'1']

或者在您的情况下,迭代“行”,然后遍历名称:

In [140]: for i,r in enumerate(t):
   .....:     print(r)
   .....:     for n in r.dtype.names:
   .....:         print(r[n])
   .....:         
(1, 1, 1.0, b'1')
1
1
1.0
b'1'
(1, 1, 1.0, b'1')
...

对于r,即0d(检查r.shape),您可以按编号选择项目或迭代

r[1]  # == r[r.dtype.names[1]]
for i in r: print(r)

对于1d的t,这不起作用; t[1]引用了一个项目。

1d结构化数组的行为有点像2d数组,但并不完全。通常关于rowcolumn的讨论必须替换为row(或项目)和field

制作可能更贴近您案例的t

In [175]: txt=[b'one-1, two-23, three-12',b'four-ab, five-ss, six-ss']

In [176]: t=np.genfromtxt(txt,dtype=[(np.str_,20),(np.str_,20),(np.str_,20)])

In [177]: t
Out[177]: 
array([('one-1,', 'two-23,', 'three-12'),
       ('four-ab,', 'five-ss,', 'six-ss')], 
      dtype=[('f0', '<U20'), ('f1', '<U20'), ('f2', '<U20')])

np.char具有可应用于数组的字符串函数:

In [178]: np.char.split(t['f0'],'-')
Out[178]: array([['one', '1,'], ['four', 'ab,']], dtype=object)

它不适用于结构化数组,但适用于各个字段。该输出可以被编入索引列表(它不是2d)。