【问题标题】:Inner join multiple csv files with python用python内部连接多个csv文件
【发布时间】:2022-01-16 11:43:44
【问题描述】:

我有一个包含 10K csv 文件的目录。每个文件有 2 列,第 1 列在所有文件中都相同。

我想根据第 1 列内部连接所有文件并获得最终输出,如下面的 sn-p 所示

#Original data of different csv files

#file1.csv
id,A
1,a1
2,a2
3,a3

#file2.csv
id,B
1,b1
2,b2
3,b3

#file3.csv
id,C
1,c1
2,c2
3,c3

#Final Output after using python script with glob pattern to operate on all csv files in a directory
id,A,B,C
1,a1,b1,c1
2,a2,b2,c2
3,a3,b3,c3

我正在使用 linux,想知道一种快速/有效的方法来实现这一点。

提前致谢。

【问题讨论】:

标签: python csv


【解决方案1】:

我尝试了 2 种方法来解决上述问题

  1. csvtk - 绝对是 csv/tsv 数据处理的好工具
  2. python 脚本

我的数据集:

 - 16,000 files - each file has 2 columns and 1000 rows
 - Column 1 of each file is the same as mentioned in the original post

csvtk 方法

my_var=$(ls -1v *csv |  perl -pe 's#\n# #g')

time csvtk join -f1 $my_var > file_merge_csvtk_join.csv

real    41m37.707s
user    196m47.658s
sys     1m6.516s

python 方法

time python join_csvs_on_column1.py  file_merge_with_python_pandas.csv

real    0m48.852s
user    0m0.024s
sys     0m0.034s

python 脚本

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# scriptName: join_csvs_on_column1.py

import pandas as pd
import glob
import os
import sys

output_file = sys.argv[1]

path = os.getcwd()

filenames = glob.glob(os.path.join(path, "*.csv"))
dfs = [pd.read_csv(filename, index_col=0) for filename in filenames]

result = dfs[0].join(dfs[1:])

result.to_csv(output_file)

以上两项测试均在:

m5.2xlarge EC2 - https://aws.amazon.com/ec2/instance-types/

 - it has 8vCPUs and 32 GiB Memory

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2015-09-09
    • 2021-03-11
    • 2018-11-08
    相关资源
    最近更新 更多