使用python删除CSV中的列 [英] Deleting columns in a CSV with python

查看:712
本文介绍了使用python删除CSV中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够使用来自这个网站上的几个用户的输入使用python创建一个csv,我想表示感谢您的帖子。

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.

我的input.csv看起来像这样:

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

我试图删除年列及其所有条目。共有40多个条目,范围从1960 - 2010年。

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.

推荐答案

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, for

        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 on 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 )

这篇关于使用python删除CSV中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆