【发布时间】:2015-11-22 05:29:57
【问题描述】:
我正在使用 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.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的转置,只需要:for col in t.T: ...? -
这很有趣 - 我会试试的
-
通常(总是?)
genfromtxt生成一维数组结构化数组。transpose什么都不做。
标签: python numpy genfromtxt