In Python, How do I read 2 CSV files, compare column 1 from both, and then write to a new file where the Column 1s match?

0 votes
If I have 2 csv files as follows:





I am looking for a Python way to compare the 2 CSV files (only Column 1), and if column1 is the same in both CSV files, then write the entire row from CSV1.csv to a new CSV file.  

So in this example, the only time column 1 is the same is '189'.  So the new output.csv file would just have 1 line, and be 189,Tom,

I have tried import pandas, csv, and every time I attempt this I am hitting a roadblock.
Jul 23, 2019 in Python by Mike
• 130 points
What's your logic? Post your workaround.

1 answer to this question.

+1 vote

Hi @Mike. First, read both the csv files and store the data in two different dataframes. Next, you will have to run a nested loop to check if the values are the same. If they are same, add that row to another dataframe and finally export the dataframe to csv. Refer to the code below:

for time1 in df1['time']:
        for time2 in df2['time']:
            if time1==time2:
answered Jul 24, 2019 by Omkar
• 69,030 points
Omkar, In this example - df1 and df2 are no defined as variables.  Can you check the code?
You can simpy use awk command to compare b/w two csv files here

$1 represent column 1

similarly if you want want to compare multiple columns then just column number as $2$3.. and so on

awk 'BEGIN{FS=","};FNR==NR{a[$1];next};($1 in a)' csv1.csv csv2.csv | cat > result.csv

Related Questions In Python

+1 vote
0 answers

Sum the values of column matching and not matching from a .txt file and write output to a two different files using Python

Name                                                    value DR_CNDAOFSZAPZP_GPFS_VOL.0 139264 DR_CNDAOFSZAPZP_GPFS_VOL.1 15657 DR_CNDAOFSZAPZP_GPFS_VOL.0 139264 DR_CNDAOFSZAPZP_GPFS_VOL.1 156579 DR_CNDAOFSZAPZP_GPFS_VOL.2 156579 DR_CNDAOFSZAPZP_GPFS_VOL.3 ...READ MORE

Nov 20, 2019 in Python by Sagar
• 130 points
0 votes
1 answer
0 votes
1 answer

how can i extact all the links from a website using python and save it in a csv file ?

Hi, @Shubham, Web scraping is the technique to ...READ MORE

answered Jun 16 in Python by Gitika
• 36,530 points
0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29, 2019 in Python by Nymeria
• 3,520 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,345 views
0 votes
0 answers
+3 votes
2 answers

how to print array integer without [] bracket in python like result = 1,2,3,4,5

Hey @abhijmr.143, you can print array integers ...READ MORE

answered Aug 4, 2018 in Python by Omkar
• 69,030 points

edited Aug 8, 2018 by Omkar 4,175 views