简体   繁体   English

如何在多个csv中搜索值并在python中创建新的csv结果?

[英]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 .这是一个使用pandasglob的简单实现。

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.

相关问题 如何在csv文件中搜索特定的列值(如果存在),使用Python将前两个列值写入新的csv文件? - How to search for a specific column value in csv file, if present , write first two column values to a new csv file with Python? 如何使用python在csv中创建多个工作表 - How to create multiple sheets in csv using python 如何在列中使用具有相同值的python中的CSV并创建具有唯一值的新CSV - How to manipulate a CSV in python with same values on a column and create a new one with unique values Python:合并多个csv文件时需要新建一列 - Python: need to create a new column when merging multiple csv files Python搜索CSV文件并在Tkinter中返回结果 - Python search CSV file and return result in Tkinter Python 使用正则表达式搜索 CSV 并将结果导出到不同的 CSV - Python Search CSV with Regex and export result to different CSV 在Python中生成具有多个值的CSV - Generate CSV with multiple values in Python Python + CSV:如何在Python中创建一个新的csv并为此写入新的列? - Python + CSV : How can I create a new csv and write new columns to that in Python? Python 将新行上的每个结果保存到 CSV - Python Saving Each Result on New Line to CSV 如何从 a.CSV 文件中找到前 10 行 AWND,并使用 Python 将结果存储在新的.CSV 文件中? - How to find the top 10 rows of AWND from a .CSV file and store the result in a new .CSV file using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM