Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace a column in a CSV file in Python?

Tags:

python

csv

I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.

Here's an example:

file1:

ID, transect, 90mdist                                      
1, a, 10,                                                  
2, b, 20,                                                
3, c, 30,     

file2:

ID, transect, 90mdist                                
1, a, 50                                                   
2, b, 70                                                     
3, c, 90          

basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.

It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?

Any help would be greatly appreciated!!

like image 307
FS. Avatar asked Jul 21 '09 14:07

FS.


People also ask

How do I find and replace in a CSV file?

When working with a CSV file it is often necessary to find data contained within and sometimes replace it. Find & Replace is used for just this. You can access it from the Edit > Find & Replace menu or by pressing Ctrl-F on the keyboard.

How do I edit a CSV file in Python?

Editing the contents of an existing CSV file will require the following steps: read in the CSV file data, edit the lists (Update information, append new information, delete information), and then write the new data back to the CSV file.


1 Answers

The CSV Module in the Python Library is what you need here.

It allows you to read and write CSV files, treating lines a tuples or lists of items.

Just read in the file with the corrected values, store the in a dictionary keyed with the line's ID.

Then read in the second file, replacing the relevant column with the data from the dict and write out to a third file.

Done.

like image 94
Ber Avatar answered Sep 29 '22 20:09

Ber