在python中使用唯一列合并两个CSV

2024-09-30 01:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个CSV文件,代表两个不同年份的数据。我知道如何使用csvwriter和dictkeys进行基本的合并,但问题在于:虽然csv主要有共享的列标题,但每个csv可能都有唯一的列。如果一个物种在一年内被捕获,而另一年没有被捕获,那么该列只会在该年出现。如何将新数据与旧数据合并,创建新列并在这些列中用零填充旧数据?在

文件1:"Date","Time","Species A","Species B", "Species X"

文件2:"Date","Time", "Species A", "Species B", "Species C"

我需要的最终结果是一个csv标题: “Date","Time","Species A","Species B", "Species C", "Species X"


Tags: 文件csv数据标题datetime物种代表
3条回答

下面是Python3中的csv模块解决方案:

import csv

# Generate some data...

csv1 = '''\
Date,Time,Species A,Species B,Species C
04/01/2012,13:00,1,2,3
04/02/2012,13:00,1,2,3
04/03/2012,13:00,1,2,3
04/04/2012,13:00,1,2,3
'''

csv2 = '''\
Date,Time,Species A,Species B,Species X
04/01/2013,13:00,1,2,3
04/02/2013,13:00,1,2,3
04/03/2013,13:00,1,2,3
04/04/2013,13:00,1,2,3
'''

with open('2012.csv','w') as f:
    f.write(csv1)
with open('2013.csv','w') as f:
    f.write(csv2)

# The actual program

years = ['2012.csv','2013.csv']

lines = []
headers = set()
for year in years:
    with open(year,'r',newline='') as f:
        r = csv.DictReader(f)
        lines.extend(list(r))                 # Merge lines from all files.
        headers = headers.union(r.fieldnames) # Collect unique column names.

# Sort the unique headers keeping Date,Time columns first.
new_headers = ['Date','Time'] + sorted(headers - set(['Date','Time']))

with open('result.csv','w',newline='') as f:
    # The 3rd parameter is the default if the key isn't present.
    w = csv.DictWriter(f,new_headers,0)
    w.writeheader()
    w.writerows(lines)

# View the result

with open('result.csv') as f:
    print(f.read())

输出:

^{pr2}$

其他人可能会使用csv模块发布一个解决方案,因此我将给出一个pandas解决方案,以便进行比较:

import pandas as pd

df1 = pd.read_csv("fish1.csv")
df2 = pd.read_csv("fish2.csv")

df = pd.concat([df1, df2]).fillna(0)
df = df[["Date", "Time"] + list(df.columns[1:-1])]
df.to_csv("merged_fish.csv", index=False)

说明:

首先,我们读了两个文件:

^{pr2}$

然后我们简单地将它们串联起来,自动用NaN填充缺失的数据:

>>> df = pd.concat([df1, df2])
>>> df
   Date  Species A  Species B  Species C  Species X  Time
0     1          3          4        NaN          5     2
1     6          8          9        NaN         10     7
2    11         13         14        NaN         15    12
0    16         18         19         20        NaN    17
1    21         23         24         25        NaN    22
2    26         28         29         30        NaN    27

您希望用0填充,因此:

>>> df = pd.concat([df1, df2]).fillna(0)
>>> df
   Date  Species A  Species B  Species C  Species X  Time
0     1          3          4          0          5     2
1     6          8          9          0         10     7
2    11         13         14          0         15    12
0    16         18         19         20          0    17
1    21         23         24         25          0    22
2    26         28         29         30          0    27

这个订单并不是您要求的,但是您需要先Time和{},所以:

>>> df = df[["Date", "Time"] + list(df.columns[1:-1])]
>>> df
   Date  Time  Species A  Species B  Species C  Species X
0     1     2          3          4          0          5
1     6     7          8          9          0         10
2    11    12         13         14          0         15
0    16    17         18         19         20          0
1    21    22         23         24         25          0
2    26    27         28         29         30          0

然后将其保存为CSV文件:

>>> df.to_csv("merged_fish.csv", index=False)

生产

Date,Time,Species A,Species B,Species C,Species X
1,2,3,4,0.0,5.0
6,7,8,9,0.0,10.0
11,12,13,14,0.0,15.0
16,17,18,19,20.0,0.0
21,22,23,24,25.0,0.0
26,27,28,29,30.0,0.0

根据docs,看起来您应该能够读取两个文件,合并2个提取字典中的键,然后使用writer上的fieldnames和{}参数来实现0默认值。在

相关问题 更多 >

    热门问题