【问题标题】:Merge one column from variable number of csv files into one csv file将可变数量的 csv 文件中的一列合并到一个 csv 文件中
【发布时间】:2016-02-24 20:05:02
【问题描述】:

这里是 Python 程序员新手。我知道有很多与此相关的 SO 帖子,但我审查过的解决方案似乎都不适合我的问题。

我有可变数量的 csv 文件,所有文件的列数都相同。第四列的标题将随每个 csv 文件而变化(它是儒略日期)。顺便说一句,这第四列存储来自卫星传感器的表面温度。举个例子:

UID,Latitude,Longitude,001
1,-151.01,45.20,13121
2,-151.13,45.16,15009
3,-151.02,45.09,10067
4,-151.33,45.03,14010

我想保留前四列(最好是我的文件列表中的第一个 csv 文件),然后将所有剩余 csv 文件中的第四列加入/合并到第一个表中。决赛桌将如下所示:

UID,Latitude,Longitude,001,007,015,023,...
1,-151.01,45.20,13121,13129,13340,12995
2,-151.13,45.16,15009,15001,14997,15103
3,-151.02,45.09,10067,11036,10074,10921
4,-151.33,45.03,14010,14005,14102,14339

我知道 Pandas 包可能是一种更简单的方法,但我宁愿在这个工具中不需要第三方包(要求用户使用 easy_install、PIP 等)。我也意识到这在 RDBMS 中会简单得多,但同样,我不希望这是一个要求。所以我只使用 csv 模块。

我想我了解如何执行此操作,并且我假设我应该将合并的行写入一个新的 csv 文件。我已经从第一个 csv 文件中提取标题,然后循环遍历每个后续 csv 文件以将新列名添加到标题行。除了第一个 csv 文件中的行之外,我的不足之处是如何仅从第四列写入值。所有 csv 文件都有 UID 列,应该匹配。

def build_table(acq_date_list, mosaic_io_array, input_dir, dir_list):
    acq_year = mosaic_io_array[0][0]
    out_dir = '%s\\%s\\' % (input_dir, dir_list[1])
    out_file = '%s%s_%s.%s' % (out_dir, 'LST_final', acq_year, 'csv')
    # get first csv file in the list of files
    first_file = acq_date_list[0][1]
    # open and read the first csv file
    with open(first_file, 'rb') as first_csv:
        r1 = csv.reader(first_csv, delimeter = ',')
        header1 = next(r1)
        allrows1 = []
        row1 = next(r1)
        allrows1.append(row1)
    # open and write to the new csv
    with open(out_file, 'wb') as out_csv:
        w = csv.writer(out_csv, delimeter = ',')
            # loop through the list of remaining csv files
            for acq_date in acq_date_list[1:]: # skip the first csv file
                # open and read other csv files
                with open(acq_date[1], 'rb') as other_csv:
                    rX = csv.reader(other_csv, delimeter = ',')
                    headerX = next(rX)
                    header_row = '%s,%s' % (header1, headerX)

                    # write header and subsequent merged rows to new csv file?

也许之后:

headerX = next(rX)

我可以将标题行拆分成一个列表,然后拉出第四项?这是否也适用于“其他”csv 文件中的剩余行。或者这只是通常的错误方法?

2016 年 2 月 26 日更新 实际上,我只是通过 Gijs 获得了部分工作的解决方案。标题列是迭代添加的,但不是行中的其余值。我仍然不确定如何用剩余 csv 文件中的值填充空单元格。

Latitude,001,UID,Longitude,009,017,025,033,041
795670.198,13506,0,-1717516.429,,,,,
795670.198,13173,1,-1716125.286,,,,,
795670.198,13502,2,-1714734.143,,,,,

【问题讨论】:

  • 每个文件有多大?你能把它们都放在记忆里吗? (认为​​将它们加载到内存中的字典可能会有所帮助)

标签: python csv


【解决方案1】:

遍历文件,跟踪存在哪些键并使用csv.DictWriter 和csv.DictReader 写入所有记录。

import csv

records = list()
all_keys = set()
for fn in ["table_1.csv", "table_2.csv"]:
    with open(fn) as f:
        reader = csv.DictReader(f)
        all_keys.update(set(reader.fieldnames))
        for r in reader:
            records.append(r)

with open("table_merged.csv", "wb") as f:
    writer = csv.DictWriter(f, fieldnames = all_keys)
    writer.writeheader()
    for r in records:
        writer.writerow(r)

这将为没有该列的记录写入一个空的“单元格”。

将您的文件作为第一个和第二个.csv,在第二种情况下,最后一列重命名为002 而不是001,您会得到:

UID,Longitude,002,001,Latitude
1,45.20,,13121,-151.01
2,45.16,,15009,-151.13
3,45.09,,10067,-151.02
4,45.03,,14010,-151.33
1,45.20,13121,,-151.01
2,45.16,15009,,-151.13
3,45.09,10067,,-151.02
4,45.03,14010,,-151.33

如果您想按特定顺序保留列,则必须将all_keys 设为list,然后仅在新文件中添加不在all_keys 中的列。

all_keys = list()

... 
         all_keys += list(set(reader.fieldnames).difference(set(all_keys)))

【讨论】:

  • 很好的解决方案!感谢您的帮助!
【解决方案2】:

尝试pandas 方法:

import pandas as pd

file_list = ['1.csv','2.csv','3.csv']

df = pd.read_csv(file_list[0])

for f in file_list[1:]:
    # use only 1-st and 4-th columns ...
    tmp = pd.read_csv(f, usecols=[0, 3])
    df = pd.merge(df, tmp, on='UID')

df.to_csv('output.csv', index=False)

print(df)

输出:

   UID  Latitude  Longitude    001    007  015
0    1   -151.01      45.20  13121  11111   11
1    2   -151.13      45.16  15009  22222   12
2    3   -151.02      45.09  10067  33333   13
3    4   -151.33      45.03  14010  44444   14

输出.csv

UID,Latitude,Longitude,001,007,015
1,-151.01,45.2,13121,11111,11
2,-151.13,45.16,15009,22222,12
3,-151.02,45.09,10067,33333,13
4,-151.33,45.03,14010,44444,14

【讨论】:

  • 这绝对是一个不错的方法,但我特别想远离这个项目的第三方包。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多