Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete columns in a CSV file?

I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will post my first question.

My input.csv looks like this:

day,month,year,lat,long 01,04,2001,45.00,120.00 02,04,2003,44.00,118.00 

I am trying to delete the "year" column and all of its entries. In total there is 40+ entries with a range of years from 1960-2010.

like image 891
Jeff Avatar asked Sep 28 '11 20:09

Jeff


People also ask

How do I delete a column in Excel CSV?

Do select [column_names] from [table] store this in a CSV file. Now you will have only required columns in the output CSV. You can use alter SQL command to delete a column but I never tried it. Another option is open the CSV using excel command and use delete column to delete the entire column.

How do you remove a column?

To remove a single column, select the column you want to remove, and then select Home > Remove Columns > Remove Columns. To remove several columns, select the columns by using Ctrl + Click or Shift + Click.


1 Answers

import csv with open("source","rb") as source:     rdr= csv.reader( source )     with open("result","wb") as result:         wtr= csv.writer( result )         for r in rdr:             wtr.writerow( (r[0], r[1], r[3], r[4]) ) 

BTW, the for loop can be removed, but not really simplified.

        in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )         wtr.writerows( in_iter ) 

Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.

            del r[2]             wtr.writerow( r ) 
like image 169
S.Lott Avatar answered Oct 23 '22 13:10

S.Lott