简体   繁体   English

如何将新列添加到现有的csv文件

[英]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.

相关问题 向现有 csv 文件添加新列 - add a new column to an existing csv file 如何基于 csv 文件中的另一列向现有 csv 文件添加新列 - How to add a new column to an existing csv file based on another column within the csv file 如何在现有csv文件的第二列中添加新列(具有标题名称)? - how to add a new column (with a header name) at the 2nd column of the existing csv file? 如何将 3 列合并为一个新列并将结果列添加到 Python 中的现有 CSV 文件(不使用 Panda) - How to merge 3 columns into a new column and add resulting column to existing CSV file in Python (without using Panda) 如何使用 CSV.Writer 在现有 CSV 文件中添加新行? - How to Add A New Row Into an Existing CSV file with CSV.Writer? 如何在不提及python中列名的情况下向现有csv文件中添加多个新列? - How to add multiple new columns to existing csv file without mentioning the column name in python? 如何向 CSV 文件添加新列? - How to add a new column to a CSV file? 如何使用Python脚本将数据添加到现有CSV中的新列中 - How to add data to the new column in existing CSV using Python script 如何使用 Python 在 csv 的现有列中添加新数据? - How to add new data in the existing column in csv with Python? 如何使用 pandas 将基于产品保质期从现有日期列派生的新日期列添加到我的 csv 文件中? - How to add a new date column derived from existing date column based on the shelf life of the products to my csv file using pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM