我有一个 .csv 文件,其中 2 个以上的空行代表一个新的数据部分。但是先验我不知道每个部分有多少行。有没有办法直接读取 pandas 数据框并在前 2+ 个空行处停止?
数据如下(来自 Google 趋势结果的 .csv 文件,此处被截断)。
Web Search interest: zts
Worldwide; 2004 - present
Interest over time
Week,zts
2004-01-04 - 2004-01-10,0
2004-01-11 - 2004-01-17,80
Top regions for zts
Region,zts
Slovakia,100
Slovenia,23
Top cities for zts
City,zts
Bratislava (Slovakia),100
Wroclaw (Poland),39
Top searches for zts
focus zts,100
ford zts,90
Rising searches for zts
2002 focus zts,Breakout
battery tester,Breakout
现在我使用 csv.reader() 并遍历所有行并保留与第一列中的日期正则表达式匹配且有两列的行。但这似乎很老套。
如果我使用类似 pandas.read_csv(input_file, header=4) 的东西(然后稍后使用日期正则表达式来找到正确的部分),那么当最后一个部分有三列时它会失败(这里没有,但可以)。
有没有办法在第一个 block 之后停止我的 pandas.read_csv() 而 a priori 不知道行数?理想情况下,我想将此 .csv 解析为五个数据帧(每个数据部分一个),但此时我很高兴捕获第一部分。
请您参考如下方法:
这是我对真实问题的解决方案,我应该将我的一个 .csv 文件解释为多个 .csv 文件,并在 pandas 之外进行拆分。
import csv
section = 1
line = 1
output_root = 'C:/Users/richard/Downloads/out'
input_file = 'C:/Users/richard/Downloads/in.csv'
input = open(input_file, 'rb')
reader = csv.reader(input)
for row in reader:
if any(row) & (line == 1):
output_file = output_root + '_' + str(section) + '.csv'
output = open(output_file, 'wb')
writer = csv.writer(output)
writer.writerow(row)
line += 1
elif any(row) & (line > 1):
writer.writerow(row)
line += 1
elif (line > 1):
output.close()
section += 1
line = 1
output.close()
input.close()
