python - 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]]
解决方案
这对你有用吗?我将您的字符串从上面转换为列表,然后遍历每一行并将其附加到最终数组
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)
推荐阅读
- html - 使用R markdown,有没有办法修复可滚动(html)、kable 表的行名,类似于scroll_box 函数修复标题行?
- asp.net-core - 在不使应用程序崩溃的情况下,循环调用命名 httpclients 的最佳方法是什么?
- iis - 使用井号/数字符号“#”重写 IIS URL
- c - 在 C 中定义全局常量
- python - TypeError: init () 只需要 1 个参数(给定 2 个)
- angular - angular oidc - 调用signinRedirect时出错
- php - 在布局中创建新行的功能无法正常工作
- scala - 是否可以在自定义 AggregateWindowFunction 中使用下一行的值
- laravel - 一次从现有数据库生成模型
- powershell - 尝试更改文件共享位置文件的时间戳时出错