How to delete columns in a CSV file?

后端 未结 9 1719
你的背包
你的背包 2020-11-27 18:05

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 po

相关标签:
9条回答
  • 2020-11-27 18:37

    Try:

    result= data.drop('year', 1)
    result.head(5)
    
    0 讨论(0)
  • 2020-11-27 18:38

    Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".

    outFile = open( 'newFile', 'w' )
    for line in open( 'oldFile' ):
       items = line.split( ',' )
       outFile.write( ','.join( items[:2] + items[ 3: ] ) )
    outFile.close()
    
    0 讨论(0)
  • 2020-11-27 18:42
    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 )
    
    0 讨论(0)
提交回复
热议问题