How to delete rows (NOT columns) in a csv file

自作多情 提交于 2019-12-25 04:40:45

问题


I am trying to delete a particular row (NOT a column) in a csv file for a class project. When I deleted columns I put:

r=row 
r[22], r[21]
# and so on

So how do I specify that I want to delete rows? I am working with census data and want to get rid of that extra row of headers that are always in census tables. Thank you for any help.


回答1:


Convert your csv reader to a list and slice the appropriate indexes off:

import csv

with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    rows = list(reader)[1:]  # no more header row



回答2:


Use pandas, it's so easy to handle data and files with it.

You can open your csv file and convert it to a pandas dataframe through.

df = pandas.reas_csv('file.csv')

After that you can use this function.

df.drop(df.columns[[0]], axis=1)

In this example I'm deleting the row with index 0.

Pandas documentation



来源:https://stackoverflow.com/questions/36945500/how-to-delete-rows-not-columns-in-a-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!