[英]How to search values in multiple csv and create new csv with result in python?
I have 5 CSV files with multiple columns and one more csv file with list of ID's.我有 5 个带有多列的 CSV 文件和一个带有 ID 列表的 csv 文件。 i have to search ID's across all 5 CSV files and create a new CSV file with results like if value present mark 1 if not mark 0.
我必须在所有 5 个 CSV 文件中搜索 ID,并创建一个新的 CSV 文件,其结果类似于如果值存在标记 1 如果不标记 0。
for example :例如 :
1.csv 1.csv
ID|身份证| NAME |ORG
名称 |组织
1 | 1 | A |B
乙 |乙
2 | 2 | C |D
C | D
7 | 7 | X |Y
X |Y
2.csv 2.csv
ID |NAME |ORG ID |名称 |组织
3 |E |F 3 |E |F
4 |G |H 4 |G |H
7 |V |U 7 |V |U
id.csv id.csv
ID ID
1 1
2 2
3 3
4 4
7 7
now result.csv should look like.现在 result.csv 应该看起来像。
result.csv结果.csv
ID |身份证 | 1.csv |2.csv
1.csv |2.csv
1 | 1 | 1 |0
1 |0
2 | 2 | 1 |0
1 |0
3 | 3 | 0 |1
0 |1
4 | 4 | 0 |1
0 |1
7 | 7 | 1 |1
1 |1
here is a simple implementation with pandas
and glob
.这是一个使用
pandas
和glob
的简单实现。
import glob
import pandas as pd
csv_files = glob.glob('[0-9].csv')
id_file = pd.read_csv('id.csv', sep='|', index_col=0)
res = pd.DataFrame(0, index=id_file.index, columns=csv_files)
for f in csv_files:
tmp = pd.read_csv(f, sep='|', index_col=0)
res.loc[id_file.index.isin(tmp.index), f] = 1
res.to_csv('result.csv', sep='|')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.