简体   繁体   English

如何删除 csv 文件中的行(不是列)

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

I am trying to delete a particular row (NOT a column) in a csv file for a class project.我正在尝试为类项目删除csv文件中的特定行(不是列)。 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.谢谢你的帮助。

Convert your csv reader to a list and slice the appropriate indexes off:将您的 csv 阅读器转换为列表并切掉适当的索引:

import csv

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

Use pandas, it's so easy to handle data and files with it.使用pandas,用它处理数据和文件非常容易。 Use it to edit your data easily.使用它可以轻松编辑您的数据。

You can open your csv file and convert it to a pandas dataframe through.您可以打开 csv 文件并将其转换为 pandas 数据框。

df = pandas.read_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.在此示例中,我将删除索引为 0 的行。

Pandas documentation熊猫文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM