![](/img/trans.png)
[英]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?
[英]How to search values in multiple csv and create new csv with result in python?
我有 5 個帶有多列的 CSV 文件和一個帶有 ID 列表的 csv 文件。 我必須在所有 5 個 CSV 文件中搜索 ID,並創建一個新的 CSV 文件,其結果類似於如果值存在標記 1 如果不標記 0。
例如 :
1.csv
身份證| 名稱 |組織
1 | 乙 |乙
2 | C | D
7 | X |Y
2.csv
ID |名稱 |組織
3 |E |F
4 |G |H
7 |V |U
id.csv
ID
1
2
3
4
7
現在 result.csv 應該看起來像。
結果.csv
身份證 | 1.csv |2.csv
1 | 1 |0
2 | 1 |0
3 | 0 |1
4 | 0 |1
7 | 1 |1
這是一個使用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.