需要删除多个 csv 文件的某些特定列和行(按索引),而不创建新文件。
对于下面的代码,它在每行之后给出带有新空白行的输出。
import csv
with open('file.csv') as fd:
reader = csv.reader(fd)
valid_rows = [row for idx, row in enumerate(reader) if idx != 0]
with open('file.csv', 'w') as out:
csv.writer(out).writerows(valid_rows)
Run Code Online (Sandbox Code Playgroud)
执行此操作的更简单方法是什么(可能是其他 python 库)?
由于您不希望生成任何新的 csv 文件并希望数据执行操作,我建议您使用Pandas Framework。在这个框架中使用drop函数。
考虑以下示例:
示例.csv:
col1,col2,col3,col4
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
17,18,19,20
Run Code Online (Sandbox Code Playgroud)
代码:
import pandas as pd
df = pd.read_csv('./Sample.csv')
Run Code Online (Sandbox Code Playgroud)
要删除列:
df.drop('col3', axis = 1, inplace = True)
Run Code Online (Sandbox Code Playgroud)
df内容:
col1 col2 col4
0 1 2 4
1 5 6 8
2 9 10 12
3 13 14 16
4 17 18 20
Run Code Online (Sandbox Code Playgroud)
要删除行:
df.drop(df.index[[1,4]], inplace = True)
Run Code Online (Sandbox Code Playgroud)
df内容:
col1 col2 col4
0 1 2 4
2 9 10 12
3 13 14 16
Run Code Online (Sandbox Code Playgroud)
最后保存编辑后的 csv 文件:
df.to_csv('new_sample.csv', index = False)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9157 次 |
| 最近记录: |