我不了解 Pandas,Python 的 CSV 模块足以胜任这项工作。
另外,你问过如何跳过一定数量的行,我的解决方案就是这样。 但是查看您的数据,我看到一行“数据”,然后是其他一些元数据行(摘要?),这代表了另一种思考您的数据的方式问题。
这是固定跳过的解决方案,之后我将介绍“相对跳过”的解决方案。
固定跳过,或跳过 n 行/行
鉴于此文件,input.csv:
id,foo
1,a
2,b
3,c
4,d
5,e
6,f
7,g
8,h
9,i
10,j
当我运行这个时:
#!/usr/bin/env python3
import csv
csv_out = open('output.csv', 'w', newline='')
writer = csv.writer(csv_out)
csv_in = open('input.csv', newline='')
reader = csv.reader(csv_in)
writer.writerow(next(reader)) # if your input CSV has a header
# Loop over rows
for row in reader:
writer.writerow(row)
try:
# next(reader) advances the CSV one row at a time; discard results
next(reader)
next(reader)
next(reader)
except StopIteration:
# The expected exception when reader runs out of rows
break
except Exception as e:
# Unexpected, raise it to user's attention
raise e
csv_in.close()
csv_out.close()
我得到了 output.csv:
id,foo
1,a
5,e
9,i
如果你想让跳过可编程:
...
SKIP_ROWS = 3
...
for row in reader:
try:
for i in range(SKIP_ROWS):
next(reader)
except StopIteration:
....
相对跳过,或跳过具有某些属性的行
如果元数据行数发生变化,跳过固定数量的行将会中断。您最好按属性跳过行。
据我所知,数据行和元数据行之间的最大区别在于,数据行有许多字段(列),而元数据行是单个字段。
...
for row in reader:
if len(row) == 1: # single column, or some other "attribute" of a row you want to skip
continue # skip it
# process your real data
...