development

csv 모듈을 사용하여 csv 파일에서 특정 열을 읽습니까?

big-blog 2020. 6. 13. 09:30
반응형

csv 모듈을 사용하여 csv 파일에서 특정 열을 읽습니까?


CSV 파일을 구문 분석하고 특정 열에서만 데이터를 추출하려고합니다.

CSV 예 :

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

나는 특정 열을 캡처 말을하기 위해 노력하고있어 ID, Name, ZipPhone.

내가 본 코드를 사용하면 특정 열을 해당 번호로 호출 할 수 있다고 생각하게되었습니다. 즉, 각 행에 Name해당 2하고 반복 row[2]하면 열 2의 모든 항목이 생성됩니다.

여기까지 내가 한 일이 있습니다.

import sys, argparse, csv
from settings import *

# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
 fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file

# open csv file
with open(csv_file, 'rb') as csvfile:

    # get number of columns
    for line in csvfile.readlines():
        array = line.split(',')
        first_item = array[0]

    num_columns = len(array)
    csvfile.seek(0)

    reader = csv.reader(csvfile, delimiter=' ')
        included_cols = [1, 2, 6, 7]

    for row in reader:
            content = list(row[i] for i in included_cols)
            print content

그리고 이것이 내가 제외하고 각 행에 대해 원하는 특정 열만 인쇄 할 것으로 기대합니다. 마지막 열만 얻습니다.


당신이 당신의 인쇄 문을 포함하지 않는 경우이 코드에서 마지막 열을 얻는 것입니다 유일한 방법은 당신의 for루프.

이것은 아마도 코드의 끝일 것입니다.

for row in reader:
    content = list(row[i] for i in included_cols)
print content

당신이 이것을 원합니다 :

for row in reader:
        content = list(row[i] for i in included_cols)
        print content

실수를 다뤘으 므로 이번에는 팬더 모듈 을 소개하겠습니다 .

팬더는 csv 파일을 다루는 데 탁월하며 다음 코드는 csv를 읽고 전체 열을 변수에 저장하는 데 필요한 모든 것입니다.

import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']

따라서 열의 모든 정보를 Names변수 에 저장 하려면 다음을 수행하십시오.

names = df.Names

훌륭한 모듈이며 살펴볼 것을 제안합니다. 어떤 이유로 인쇄 문이 for루프 상태이고 여전히 마지막 열만 인쇄하는 경우에는 발생하지 않아야하지만 내 가정이 잘못되었는지 알려주십시오. 게시 된 코드에는 들여 쓰기 오류가 많으므로 어디에 있어야하는지 알기가 어렵습니다. 이것이 도움이 되었기를 바랍니다!


import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('file.txt') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value 
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

print(columns['name'])
print(columns['phone'])
print(columns['street'])

같은 파일로

name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.

출력

>>> 
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']

또는 열에 대한 숫자 색인을 생성하려는 경우 :

with open('file.txt') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
print(columns[0])

>>> 
['Bob', 'James', 'Smithers']

델리 미네 이터를 변경하려면 delimiter=" "적절한 인스턴스화에 추가하십시오.reader = csv.reader(f,delimiter=" ")


팬더 사용 :

import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']

구문 분석시 불필요한 열을 폐기하십시오.

my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

추신 : 나는 다른 사람들이 말한 것을 간단한 방식으로 모으고 있습니다. 실제 답변은 여기여기 에서 가져옵니다 .


With pandas you can use read_csv with usecols parameter:

df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

Example:

import pandas as pd
import io

s = '''
total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
'''

df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])
print(df)

   total_bill  day  size
0       16.99  Sun     2
1       10.34  Sun     3
2       21.01  Sun     3

You can use numpy.loadtext(filename). For example if this is your database .csv:

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | Adam | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Carl | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Adolf | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Den | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

And you want the Name column:

import numpy as np 
b=np.loadtxt(r'filepath\name.csv',dtype=str,delimiter='|',skiprows=1,usecols=(1,))

>>> b
array([' Adam ', ' Carl ', ' Adolf ', ' Den '], 
      dtype='|S7')

More easily you can use genfromtext:

b = np.genfromtxt(r'filepath\name.csv', delimiter='|', names=True,dtype=None)
>>> b['Name']
array([' Adam ', ' Carl ', ' Adolf ', ' Den '], 
      dtype='|S7')

Context: For this type of work you should use the amazing python petl library. That will save you a lot of work and potential frustration from doing things 'manually' with the standard csv module. AFAIK, the only people who still use the csv module are those who have not yet discovered better tools for working with tabular data (pandas, petl, etc.), which is fine, but if you plan to work with a lot of data in your career from various strange sources, learning something like petl is one of the best investments you can make. To get started should only take 30 minutes after you've done pip install petl. The documentation is excellent.

Answer: Let's say you have the first table in a csv file (you can also load directly from the database using petl). Then you would simply load it and do the following.

from petl import fromcsv, look, cut, tocsv 

#Load the table
table1 = fromcsv('table1.csv')
# Alter the colums
table2 = cut(table1, 'Song_Name','Artist_ID')
#have a quick look to make sure things are ok. Prints a nicely formatted table to your console
print look(table2)
# Save to new file
tocsv(table2, 'new.csv')

import pandas as pd 
csv_file = pd.read_csv("file.csv") 
column_val_list = csv_file.column_name._ndarray_values

To fetch column name, instead of using readlines() better use readline() to avoid loop & reading the complete file & storing it in the array.

with open(csv_file, 'rb') as csvfile:

    # get number of columns

    line = csvfile.readline()

    first_item = line.split(',')

Thanks to the way you can index and subset a pandas dataframe, a very easy way to extract a single column from a csv file into a variable is:

myVar = pd.read_csv('YourPath', sep = ",")['ColumnName']

A few things to consider:

The snippet above will produce a pandas Series and not dataframe. The suggestion from ayhan with usecols will also be faster if speed is an issue. Testing the two different approaches using %timeit on a 2122 KB sized csv file yields 22.8 ms for the usecols approach and 53 ms for my suggested approach.

And don't forget import pandas as pd


If you need to process the columns separately, I like to destructure the columns with the zip(*iterable) pattern (effectively "unzip"). So for your example:

ids, names, zips, phones = zip(*(
  (row[1], row[2], row[6], row[7])
  for row in reader
))

참고URL : https://stackoverflow.com/questions/16503560/read-specific-columns-from-a-csv-file-with-csv-module

반응형