问题
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