Programing

CSV 데이터를 처리 할 때 데이터의 첫 줄을 무시하려면 어떻게해야합니까?

lottogame 2020. 8. 17. 09:31
반응형

CSV 데이터를 처리 할 때 데이터의 첫 줄을 무시하려면 어떻게해야합니까?


Python에 CSV 데이터 열에서 최소 수를 인쇄하도록 요청하고 있지만 맨 위 행은 열 번호이며 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을 처음 접했고 모든 것을 이해하고 있는지 확인하고 싶습니다.


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)

이후 datatypecolumn귀하의 예제에 하드 코딩되어, 그것을 처리하기 위해 약간 빠른 것 row같은를 :

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

참고 : 위 코드는 Python 3.x 용입니다. Python 2.x의 경우 다음 줄을 사용하여 표시된 파일 대신 파일을 엽니 다.

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

첫 번째 줄을 건너 뛰려면 다음을 호출하십시오.

next(inf)

Python의 파일은 행에 대한 반복자입니다.


일반적으로 next(incsv)반복자를 한 행 앞당기는 것을 사용 하므로 헤더를 건너 뜁니다. 다른 하나 (30 행을 건너 뛰고 싶었다고 가정)는 다음과 같습니다.

from itertools import islice
for row in islice(incsv, 30, None):
    # process

유사한 사용 사례에서 실제 열 이름이있는 줄 앞에 성가신 줄을 건너 뛰어야했습니다. 이 솔루션은 잘 작동했습니다. 먼저 파일을 읽은 다음 목록을 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)))

에서 차용 파이썬 요리 책 ,
더 간결 템플릿 코드는 다음과 같습니다

import csv
with open('stocks.csv') as f:
    f_csv = csv.reader(f) 
    headers = next(f_csv) 
    for row in f_csv:
        # Process row ...

use csv.DictReader instead of csv.Reader. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as field names. you would then be able to access field values using row["1"] etc


The new 'pandas' package might be more relevant than 'csv'. The code below will read a CSV file, by default interpreting the first line as the column header and find the minimum across columns.

import pandas as pd

data = pd.read_csv('all16.csv')
data.min()

Well, my mini wrapper library would do the job as well.

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

Meanwhile, if you know what header column index one is, for example "Column 1", you can do this instead:

>>> min(data.column["Column 1"])

For me the easiest way to go is to use range.

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])  

Because this is related to something I was doing, I'll share here.

What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?

If your task is basic, such as printing or appending to a list or array, you could just use an if statement:

# 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)

The documentation for the Python 3 CSV module provides this example:

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 ...

The Sniffer will try to auto-detect many things about the CSV file. You need to explicitly call its has_header() method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:

if sniffer.has_header():
    for header_row in reader:
        break
for data_row in reader:
    # do something with the row

I would use tail to get rid of the unwanted first line:

tail -n +2 $INFIL | whatever_script.py 

just add [1:]

example below:

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

that works for me in iPython


Python 3.X

Handles UTF8 BOM + HEADER

It was quite frustrating that the csv module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file). This works for me using only the csv module:

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]

참고URL : https://stackoverflow.com/questions/11349333/when-processing-csv-data-how-do-i-ignore-the-first-line-of-data

반응형