【问题标题】:How to add a column value from a .csv to another one when the other columns are the same?当其他列相同时,如何将 .csv 中的列值添加到另一个列?
【发布时间】:2017-03-25 03:43:50
【问题描述】:

我有两个 .csv 文件:File1=28 列和 1000 行,File2=29 列和 100 行。该行没有索引,因此,我不知道两个文件中哪些行相同。

对于文件 1 中的每一行,当其他 28 列相同时,我想在 File2 中添加一个值为 29 的新列。

File1:
a,b,c,...,EMPTY
x,y,z,...,EMPTY

File2:
a,b,c,...,B1
x,y,z,...,B2

Output:
a,b,c,...,B1
x,y,z,...,B2

到目前为止,我还处于起步阶段;

with open(('File1.csv', 'rb'), delimiter=';') as test1:
    reader = csv.reader(test1)
    next(reader, None)  # ignore header
    test1 = set(row[0:28] for row in reader)
with open(('File2.csv', 'rb'), delimiter=';') as test2:
    reader = csv.reader(test2)
    next(reader, None)  # ignore header
    test2 = set(row[0:28] for row in reader)

【问题讨论】:

  • 欢迎来到 SO 请查看stackoverflow.com/help/formatting 以获取有关格式化您下一个问题或答案的帮助。
  • 匹配的行是否总是在文件中的同一行号? File2 中是否存在缺少信息的行?
  • 不,它们不在同一行,File1 有 40000 行,File2 有 2000 行。

标签: python csv


【解决方案1】:

我建议使用numpy.loadtxt 来加载两个 csv 文件,因为它更高效,并且为内容提供了结构。然后,您将有一个数组 f1 的 1000 X 28 值的 File1 和一个数组 f2 的 100 X 29 的 File2。

第二步是使用 f1 = numpy.column_stack([f1, numpy.zeros(f1.shape[0])]) 向 File1 添加一个新列。

然后,您可以遍历最小的数组:

for row in f2:
    # find the row(s) in f1 with the same 28 first columns
    equal_rows = np.argwhere((f1[:, :28] == row[:28]).all(axis=1))
    for row2 in equal_rows:
        # add the last column of f2
        f1[row2[0], -1] = row[-1]

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2022-01-04
    • 2020-06-04
    • 2021-08-12
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多