社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中跳过读取CSV文件的第一行?

Atish Banerjee • 5 年前 • 4143 次点击  

我要求Python打印CSV数据列中的最小值,但是最上面的行是列号,我不希望Python考虑最上面的行。如何确保Python忽略第一行?

这是目前为止的代码:

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

你能解释一下你在做什么,而不仅仅是给出代码吗?我对Python很陌生,我想确保我理解所有内容。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51949
 
4143 次点击  
文章 [ 14 ]  |  最新文章 5 年前
Christophe Roussy
Reply   •   1 楼
Christophe Roussy    8 年前

巨蟒3.X

处理UTF8物料清单+标题

令人沮丧的是 csv 模块无法轻松获取头文件,UTF-8bom(文件中的第一个字符)也有一个错误。 这对我来说很管用 csv公司 模块:

import csv

def read_csv(self, csv_path, delimiter):
    with open(csv_path, newline='', encoding='utf-8') as f:
        # https://bugs.python.org/issue7185
        # Remove UTF8 BOM.
        txt = f.read()[1:]

    # Remove header line.
    header = txt.splitlines()[:1]
    lines = txt.splitlines()[1:]

    # Convert to list.
    csv_rows = list(csv.reader(lines, delimiter=delimiter))

    for row in csv_rows:
        value = row[INDEX_HERE]
cricket_007 aybuke
Reply   •   2 楼
cricket_007 aybuke    9 年前

只需添加 [1:]

示例如下:

data = pd.read_csv("/Users/xyz/Desktop/xyxData/xyz.csv", sep=',', header=None)**[1:]**

在伊普顿对我有用

Karel Adams
Reply   •   3 楼
Karel Adams    9 年前

我会用 要去掉不需要的第一行:

tail -n +2 $INFIL | whatever_script.py 
Lassi
Reply   •   4 楼
Lassi    6 年前

这个 documentation for the Python 3 CSV module 提供以下示例:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

这个 Sniffer 将尝试自动检测CSV文件的许多内容。你需要显式地调用它 has_header() 方法来确定文件是否具有标题行。如果是,则在迭代CSV行时跳过第一行。你可以这样做:

if sniffer.has_header():
    for header_row in reader:
        break
for data_row in reader:
    # do something with the row
Roy W.
Reply   •   5 楼
Roy W.    7 年前

因为这和我正在做的事情有关,我将在这里分享。

如果我们不确定是否有一个头,而您也不想导入嗅探器和其他东西呢?

如果您的任务是基本的,例如打印或附加到列表或数组,则可以使用If语句:

# Let's say there's 4 columns
with open('file.csv') as csvfile:
     csvreader = csv.reader(csvfile)
# read first line
     first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
     if len(first_line) == 4:
          array.append(first_line)
# Now we'll just iterate over everything else as usual:
     for row in csvreader:
          array.append(row)
Clint Hart
Reply   •   6 楼
Clint Hart    7 年前

对我来说最简单的方法就是使用射程。

import csv

with open('files/filename.csv') as I:
    reader = csv.reader(I)
    fulllist = list(reader)

# Starting with data skipping header
for item in range(1, len(fulllist)): 
    # Print each row using "item" as the index value
    print (fulllist[item])  
chfw
Reply   •   7 楼
chfw    10 年前

好吧,我的 mini wrapper library 也能胜任这项工作。

>>> import pyexcel as pe
>>> data = pe.load('all16.csv', name_columns_by_row=0)
>>> min(data.column[1])

同时,如果您知道标题列索引1是什么,例如“column 1”,则可以执行以下操作:

>>> min(data.column["Column 1"])
Finn Årup Nielsen
Reply   •   8 楼
Finn Årup Nielsen    10 年前

新的“熊猫”软件包可能比“csv”更有意义。下面的代码将读取一个CSV文件,默认情况下,将第一行解释为列标题,并找到跨列的最小值。

import pandas as pd

data = pd.read_csv('all16.csv')
data.min()
iruvar
Reply   •   9 楼
iruvar    13 年前

使用csv.DictReader而不是csv.Reader。 如果省略field names参数,则csvfile的第一行中的值将用作字段名。然后您就可以使用第[“1”]行等访问字段值

shin
Reply   •   10 楼
shin    7 年前

借来的 python cookbook ,
更简洁的模板代码可能如下所示:

import csv
with open('stocks.csv') as f:
    f_csv = csv.reader(f) 
    headers = next(f_csv) 
    for row in f_csv:
        # Process row ...
Veedrac Maarten
Reply   •   11 楼
Veedrac Maarten    10 年前

在类似的用例中,我不得不在实际列名所在的行之前跳过恼人的行。这个解决方案很有效。先读取文件,然后将列表传递给 csv.DictReader .

with open('all16.csv') as tmp:
    # Skip first line (if any)
    next(tmp, None)

    # {line_num: row}
    data = dict(enumerate(csv.DictReader(tmp)))
Jon Clements
Reply   •   12 楼
Jon Clements    13 年前

你通常会使用 next(incsv) 将迭代器向前推进一行,这样就跳过了头。另一个(比如你想跳过30行)是:

from itertools import islice
for row in islice(incsv, 30, None):
    # process
jfs
Reply   •   13 楼
jfs    13 年前

要跳过第一行,请拨打:

next(inf)

Python中的文件是行上的迭代器。

martineau
Reply   •   14 楼
martineau    5 年前

您可以使用 csv 模块的 Sniffer 类来推断CSV文件的格式,并检测是否存在头行以及内置的 next() 函数仅在必要时跳过第一行:

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)

自从 datatype column 在您的示例中是硬编码的,处理 row 这样地:

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

注: 上面的代码适用于Python3.x。对于Python2.x,请使用以下行打开文件,而不是显示:

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