Python Numpy genfromtxt在列上迭代

Python Numpy genfromtxt在列上迭代,python,numpy,genfromtxt,Python,Numpy,Genfromtxt,我正在使用NumPy的genfromtext从CSV文件中获取列 每个列都需要拆分并分配给一个单独的SQLAlchemySystemRecord,与其他一些列和属性组合,并添加到数据库中 迭代列f1到f9并将它们添加到会话对象的最佳实践是什么 到目前为止,我使用了以下代码,但我不想对每个f列执行相同的操作: t = np.genfromtxt(FILE_NAME,dtype=[(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.str_, 20),(np.

我正在使用
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()

查看
t.dtype
。或
r.dtype

制作一个示例结构化数组(这是genfromtxt返回的):

这看起来像:

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')])
迭代名称以查看各个列:

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]引用项目

一维结构化数组的行为有点像二维数组,但不完全一样。通常所说的
必须替换为
(或项目)和
字段


使
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')])

它不适用于结构化数组,但适用于单个字段。该输出可以作为列表列表(不是2d)进行索引。

不可能对
t
的转置进行迭代,只需对t中的col执行
。t:…
?这很有趣-我通常(总是?)尝试
genfromtxt
生成一个1d数组结构数组<代码>转置不执行任何操作。
r[1]  # == r[r.dtype.names[1]]
for i in r: print(r)
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')])
In [178]: np.char.split(t['f0'],'-')
Out[178]: array([['one', '1,'], ['four', 'ab,']], dtype=object)