mysql e 忽略第一行,处理CSV数据时如何忽略第一行数据?

该博客介绍了如何使用Python读取CSV文件并忽略第一行(即头部行)来找到某一列的最小值。通过使用csv模块的Sniffer类判断文件是否有头部,然后结合next()函数跳过头部,最终计算最小值。代码适用于Python3.x,对于Python2.x需调整文件打开方式。
摘要由CSDN通过智能技术生成

I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?

This is the code so far:

import csv

with open('all16.csv', 'rb') as inf:

incsv = csv.reader(inf)

column = 1

datatype = float

data = (datatype(column) for row in incsv)

least_value = min(data)

print least_value

Could you also explain what you are doing, not just give the code? I am very very new to Python and would like to make sure I understand everything.

解决方案

You could use an instance of the csv module's Sniffer class to deduce the format of a CSV file and detect whether a header row is present along with the built-in next() function to skip over the first row only when necessary:

import csv

with open('all16.csv', 'r', newline='') as file:

has_header = csv.Sniffer().has_header(file.read(1024))

file.seek(0) # Rewind.

reader = csv.reader(file)

if has_header:

next(reader) # Skip header row.

column = 1

datatype = float

data = (datatype(row[column]) for row in reader)

least_value = min(data)

print(least_value)

Since datatype and column are hardcoded in your example, it would be slightly faster to process the row like this:

data = (float(row[1]) for row in reader)

Note: the code above is for Python 3.x. For Python 2.x use the following line to open the file instead of what is shown:

with open('all16.csv', 'rb') as file:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值