Skip to content
Advertisement

Joining two CSV files with common column in Python without Pandas

I wanted to inquire on how I could merge 2 csv files so that I can generate queries. Note that I am not allowed to use the “pandas” library.

As an example I have these 2 csv:

data.csv:

JavaScript

enti.csv:

JavaScript

And what I’m looking for is to be able to join them through cod_enti and thus be able to evaluate the number of cod_pers that they have as cod_mercado = 40 in the last 15 days.

For this I understand that I can generate the reading of the csv files as follows:

JavaScript

And later to be able to search by days with a method similar to this:

JavaScript

But for this I must first join the 2 csv files to be able to generate the query.

I look forward to your comments and any kind of help, it is appreciated. Thank you!! :D

MODIFICATION:

I have added the following lines to my code:

JavaScript

And it works correctly, but when I want to enter csv with more data, it gives me the following error:

JavaScript

Advertisement

Answer

You can do this in pretty straight-forward approach with just the CSV module.

I create a map of each row in data.csv to its code_enti value. Then, for every row in enti.csv that has a matching code_enti, I update the row in the map:

JavaScript

Here’s what I get when I run that:

JavaScript

From there, you can extract the rows into a normal list and do all your filtering by key-value, or however else.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement