我有两个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"
下面是Python3中的
csv
模块解决方案:输出:
^{pr2}$其他人可能会使用
csv
模块发布一个解决方案,因此我将给出一个pandas解决方案,以便进行比较:说明:
首先,我们读了两个文件:
^{pr2}$然后我们简单地将它们串联起来,自动用
NaN
填充缺失的数据:您希望用0填充,因此:
这个订单并不是您要求的,但是您需要先},所以:
Time
和{然后将其保存为CSV文件:
生产
根据docs,看起来您应该能够读取两个文件,合并2个提取字典中的键,然后使用writer上的}参数来实现0默认值。在
fieldnames
和{相关问题 更多 >
编程相关推荐