首页 > 解决方案 > Python,从 csvs 操作数组并插入数据库

问题描述

我想将多个 csv 文件作为数组读取,并根据每行中第一个条目的数值复制这些数组的行(如果值为 1,则不重复,但如果值为 3行表示 3 次)。操作数组后,我想将它们插入到数据库表中。

示例 csv 文件:

mult, n1, n2, n3, n4
1, 23.2, 55, 0, 1.1
3, 6.6, 0.2, 5, 9
1, 2.2, 5, 8, 9
2, 3.3, 10, 2, 2

mult, n1, n2, n3, n4
2, 23.2, 55, 0, 1.1
3, 6.6, 0.2, 5, 9
1, 2.2, 5, 8, 9
1, 3.3, 10, 2, 2

期望的结果

[[1, 23.2, 55, 0, 1.1],
[3, 6.6, 0.2, 5, 9],
[3, 6.6, 0.2, 5, 9],
[3, 6.6, 0.2, 5, 9],
[1, 2.2, 5, 8, 9],
[2, 3.3, 10, 2, 2],
[2, 3.3, 10, 2, 2]]

[[2, 23.2 55, 0, 1.1],
[2, 23.2 55, 0, 1,1],
[3, 6.6, 0.2, 5, 9],
[3, 6.6, 0.2, 5, 9],
[3, 6.6, 0.2, 5, 9],
[1, 2.2, 5, 8, 9],
[1, 3.3, 10, 2, 2]]

最初我将 csvs 作为列表读取,然后有一个 for 循环根据 row[0] 中的数字将每一行插入到数据库中

当前工作的基本代码片段:

import csv, os, glob
import psycopg2

path = "/home/user/Desktop/files/*.csv"

for fname in glob.glob(path):
    self.readFile(fname)

with open(filename, 'r') as f:
    arr= list(csv.reader(f)) 
    iter_arr = iter(arr)
    next(iter_arr)

    for row in iter_arr:                   
        mult = int(float(row[0]))
        for i in range (mult):
            try:
                self.cur.execute("INSERT INTO csv_table VALUES (%s, %s, %s, %s, %s)", row)

             except Exception, exc:     
                 locked = True
                 print ("%s", exc)     

上面的代码的工作原理是它将在数据库表中加载正确数量的行,但我认为在将行加载到数据库之前复制行会更有用,这样如果我可以进一步操作数组中的数据需要,例如更改或添加值。

我之前问过一个关于使用 numpy 的问题,它允许我正确操作一些随机生成的数组,但不是将行复制为单独的元素,而是将它们相互复制。我不知道如何调整它的大小以使其正常工作,而且看起来很像。调整大小似乎不起作用,我得到了('%s', TypeError('not all arguments converted during string formatting',))

a = ([list(map(float, row)) for row in csv.reader(f)])
aa = np.asarray(a)
result = ([np.tile(aa[i], aa[i, 1].astype(int)) for i in range(aa.shape[0])])result = np.asarray(result)

结果

[[1, 23.2, 55, 0, 1.1],
[3, 6.6, 0.2, 5, 9,
3, 6.6, 0.2, 5, 9,
3, 6.6, 0.2, 5, 9],
[1, 2.2, 5, 8, 9],
[2, 3.3, 10, 2, 2,
2, 3.3, 10, 2, 2]]

[[2, 23.2 55, 0, 1.1,
2, 23.2 55, 0, 1,1],
[3, 6.6, 0.2, 5, 9,
3, 6.6, 0.2, 5, 9,
3, 6.6, 0.2, 5, 9],
[1, 2.2, 5, 8, 9],
[1, 3.3, 10, 2, 2]]

标签: pythonarrayspostgresqlcsv

解决方案


这对你有用吗?我将您的字符串从上面转换为列表,然后遍历每一行并将其附加到最终数组

a = """mult, n1, n2, n3, n4
1, 23.2, 55, 0, 1.1
3, 6.6, 0.2, 5, 9
1, 2.2, 5, 8, 9
2, 3.3, 10, 2, 2
2, 23.2, 55, 0, 1.1
3, 6.6, 0.2, 5, 9
1, 2.2, 5, 8, 9
1, 3.3, 10, 2, 2"""

a = a.split('\n')

final = a[0]
for line in a[1:]:
    for i in range(int(line[0])):
        final.append(line)

推荐阅读