Home > Net >  Joining two CSV files (inner join) with common column in Python without Pandas
Joining two CSV files (inner join) with common column in Python without Pandas

Time:04-15

I have 2 files:

data.csv:

cod_pers, cod_enti, fec_venc
2317422,208,04/12/2022
2392115,210,04/02/2022
2086638,211,31/03/2022
2086638,212,03/13/2022

enti.csv:

cod_enti,cod_market
208,40
209,50
210,16
211,40
212,50

So I want a output file containing :

cod_pers, cod_enti, fec_venc, cod_market
2317422,208,04/12/2022,40
2392115,210,04/02/2022,16
2086638,211,31/03/2022,40
2086638,212,03/13/2022,50

How should I do it? I have written the code below:

import csv
import numpy as np
from time import strftime
from datetime import datetime, date, time, timedelta
from dateutil.relativedelta import relativedelta

#Read the CSV file
str2date = lambda x: datetime.strptime(x, '%d/%m/%Y')
data_datos = np.genfromtxt(r'data.csv', delimiter=',', dtype=None, names=True, converters={'fec_venc':str2date}, encoding="UTF-8")
data_enti = np.genfromtxt(r'enti.csv', delimiter=',', dtype=None, names=True, encoding="UTF-8")

CodePudding user response:

from numpy.lib import recfunctions
# your code to import csv
merged_array = recfunctions.join_by('cod_enti', data_datos, data_enti)

See this doc

  • Related