[英]How to add new column to existing csv file
For instance, x is my data and r is supposed to be new data to be added. 例如, x是我的数据,而r应该是要添加的新数据。
import numpy as np
x = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], np.int32)
np.savetxt("test.csv", x, fmt='%d', delimiter=',')
r = [1,2,3]
how could I add it to that "test.csv" 如何将其添加到“ test.csv”中
您可以使用numpy中的insert函数插入新列,如下所示
np.insert(x, 3, [r], axis=1)
Isn't this just about adding a column to an existing 2d array. 这不只是要将列添加到现有的2d数组中。 Writing it to a csv file is just a further step and isn't affected by this addition.
将其写入csv文件只是进一步的步骤,不受此添加操作的影响。
In [96]: x = np.array([[1, 2, 3],
...: [4, 5, 6],
...: [7, 8, 9]], np.int32)
In [97]: r = [1,2,3]
There are a number of functions that can add a column to an array, but they all end up using concatenate
. 有许多函数可以将一列添加到数组中,但最终都使用
concatenate
。 And knowing how to use concatenate
directly is a good thing to know. 知道如何直接使用
concatenate
是一件好事。 The key is matching the number of dimensions. 关键是匹配尺寸数。
In [98]: x1 = np.concatenate((x, np.array(r)[:,None]), axis=1)
In [99]: x1
Out[99]:
array([[1, 2, 3, 1],
[4, 5, 6, 2],
[7, 8, 9, 3]])
vstack
takes care of turning r
into this column array. vstack
负责将r
变成此列数组。 insert
is more general, allowing you to add values within the existing (not just at the end). insert
法比较笼统,允许您在现有值(而不是最后)中添加值。 But like concatenate
(and all the stacks) it does not operate in-place. 但是像
concatenate
(和所有堆栈)一样,它不能就地运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.