[英]Python CSVkit compare CSV files
I have two CSV files that look like this..我有两个 CSV 文件,看起来像这样..
CSV 1 CSV 1
reference | name | house
----------------------------
2348A | john | 37
5648R | bill | 3
RT48 | kate | 88
76A | harry | 433
CSV2 CSV2
reference
---------
2348A
76A
Using Python and CSVkit I am trying to create an output CSV of the rows in CSV1 by comparing it to CSV2.使用 Python 和 CSVkit 我试图通过将它与 CSV2 进行比较来创建 CSV1 中行的输出 CSV。 Does anybody have an example they can point me in the direction of?
有没有人有一个例子,他们可以指出我的方向?
I would recommended to use pandas
to achieve what you are looking for:我建议使用
pandas
来实现您的目标:
And here is how simple it would be using pandas, consider your two csv files are like this:这是使用熊猫的简单方式,考虑到您的两个 csv 文件是这样的:
CSV1
reference,name,house
2348A,john,37
5648R,bill,3
RT48,kate,88
76A,harry ,433
CSV2
reference
2348A
76A
Code
代码
import pandas as pd
df1 = pd.read_csv(r'd:\temp\data1.csv')
df2 = pd.read_csv(r'd:\temp\data2.csv')
df3 = pd.merge(df1,df2, on= 'reference', how='inner')
df3.to_csv('outpt.csv')
output.csv
输出.csv
,reference,name,house
0,2348A,john,37
1,76A,harry ,433
I'd recommend using a tool like csvjoin from csvkit我建议使用csvkit 中的csvjoin 之类的工具
pip install csvkit
$ csvjoin --help
usage: csvjoin [-h] [-d DELIMITER] [-t] [-q QUOTECHAR] [-u {0,1,2,3}] [-b]
[-p ESCAPECHAR] [-z MAXFIELDSIZE] [-e ENCODING] [-S] [-v] [-l]
[--zero] [-c COLUMNS] [--outer] [--left] [--right]
[FILE [FILE ...]]
Example: Left Join on column of [reference]示例:左连接 [reference] 的列
csvjoin --columns "reference" --left CSV1.csv CSV2.csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.