Tôi đang cố gắng phân tích thông qua tệp CSV và trích xuất dữ liệu từ các cột cụ thể.
Ví dụ CSV:
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
Tôi đang cố gắng nắm bắt các cột cụ thể, giả sử
for row in reader:
content = list[row[i] for i in included_cols]
print content
7, for row in reader:
content = list[row[i] for i in included_cols]
print content
8, for row in reader:
content = list[row[i] for i in included_cols]
print content
9 và for row in reader:
content = list[row[i] for i in included_cols]
print content
0.Mã tôi đã xem đã khiến tôi tin rằng tôi có thể gọi cột cụ thể theo số tương ứng của nó, vì vậy IE:
for row in reader:
content = list[row[i] for i in included_cols]
print content
8 sẽ tương ứng với for row in reader:
content = list[row[i] for i in included_cols]
print content
2 và lặp qua mỗi hàng bằng cách sử dụng for row in reader:
content = list[row[i] for i in included_cols]
print content
3 sẽ tạo ra tất cả các mục trong cột 2. Chỉ có nó ' t.Đây là những gì tôi đã làm cho đến nay:
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
Và tôi hy vọng rằng điều này sẽ chỉ in ra các cột cụ thể mà tôi muốn cho mỗi hàng ngoại trừ nó không, tôi chỉ nhận được cột cuối cùng.
Martineau
Huy hiệu vàng 116K2525 gold badges161 silver badges286 bronze badges
Khi được hỏi ngày 12 tháng 5 năm 2013 lúc 2:10May 12, 2013 at 2:10
4
Cách duy nhất bạn sẽ nhận được cột cuối cùng từ mã này là nếu bạn không đưa câu lệnh in của mình vào vòng lặp
for row in reader:
content = list[row[i] for i in included_cols]
print content
4 của mình.in your for row in reader:
content = list[row[i] for i in included_cols]
print content
4 loop. Đây rất có thể là kết thúc mã của bạn:
for row in reader:
content = list[row[i] for i in included_cols]
print content
Bạn muốn nó là thế này:
for row in reader:
content = list[row[i] for i in included_cols]
print content
Bây giờ chúng tôi đã đề cập đến sai lầm của bạn, tôi muốn dành thời gian này để giới thiệu bạn với mô -đun Pandas.
Pandas là ngoạn mục để xử lý các tệp CSV và mã sau đây sẽ là tất cả những gì bạn cần để đọc CSV và lưu toàn bộ cột vào một biến:
import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
Vì vậy, nếu bạn muốn lưu tất cả thông tin trong cột của mình
for row in reader:
content = list[row[i] for i in included_cols]
print content
5 vào một biến, đây là tất cả những gì bạn cần làm:names = df.Names
Đó là một mô -đun tuyệt vời và tôi khuyên bạn nên xem xét nó. Nếu vì một lý do nào đó, câu lệnh in của bạn là trong vòng lặp
for row in reader:
content = list[row[i] for i in included_cols]
print content
4 và nó vẫn chỉ in ra cột cuối cùng, điều này không nên xảy ra, nhưng hãy cho tôi biết nếu giả định của tôi là sai. Mã được đăng của bạn có rất nhiều lỗi thụt nh cứu nên thật khó để biết những gì được cho là ở đâu. Hy vọng điều này là hữu ích!Đã trả lời ngày 12 tháng 5 năm 2013 lúc 3:06May 12, 2013 at 3:06
Ryan Saxeryan SaxeRyan Saxe
16.5K22 Huy hiệu vàng78 Huy hiệu bạc124 Huy hiệu đồng22 gold badges78 silver badges124 bronze badges
3
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']]
Với một tệp như
name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.
Sẽ đầu ra
>>>
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']
Hoặc cách khác nếu bạn muốn lập chỉ mục số cho các cột:
with open['file.txt'] as f:
reader = csv.reader[f]
next[reader]
for row in reader:
for [i,v] in enumerate[row]:
columns[i].append[v]
print[columns[0]]
>>>
['Bob', 'James', 'Smithers']
Để thay đổi DELIMINATOR Thêm
for row in reader:
content = list[row[i] for i in included_cols]
print content
7 thành khởi tạo thích hợp, tức là for row in reader:
content = list[row[i] for i in included_cols]
print content
8
Subash
8318 Huy hiệu bạc19 Huy hiệu đồng8 silver badges19 bronze badges
Đã trả lời ngày 12 tháng 5 năm 2013 lúc 2:34May 12, 2013 at 2:34
HennyhhennyhHennyH
7.6442 Huy hiệu vàng28 Huy hiệu bạc38 Huy hiệu đồng2 gold badges28 silver badges38 bronze badges
0
Sử dụng gấu trúc:
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
0Loại bỏ các cột không cần thiết tại thời điểm phân tích:
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
1P.S. Tôi chỉ tổng hợp những gì người khác đã nói một cách đơn giản. Câu trả lời thực tế được lấy từ đây và đây.
Đã trả lời ngày 23 tháng 5 năm 2017 lúc 9:05May 23, 2017 at 9:05
VasilinovikovvasilinovikovVasiliNovikov
9.0703 Huy hiệu vàng45 Huy hiệu bạc60 Huy hiệu Đồng3 gold badges45 silver badges60 bronze badges
2
Bạn có thể sử dụng
for row in reader:
content = list[row[i] for i in included_cols]
print content
9. Ví dụ: nếu đây là cơ sở dữ liệu của bạn import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
0: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
2Và bạn muốn cột
for row in reader:
content = list[row[i] for i in included_cols]
print content
8: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
3Dễ dàng hơn bạn có thể sử dụng
import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
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
4Đã trả lời ngày 10 tháng 1 năm 2014 lúc 13:46Jan 10, 2014 at 13:46
G mg mG M
Phù hiệu vàng 19K1077 Huy hiệu bạc80 Huy hiệu đồng10 gold badges77 silver badges80 bronze badges
1
Với gấu trúc, bạn có thể sử dụng
import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
3 với tham số import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
4: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
5Example:
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
6Đã trả lời ngày 6 tháng 12 năm 2016 lúc 20:26Dec 6, 2016 at 20:26
Ayhanayhanayhan
66.9K18 Huy hiệu vàng173 Huy hiệu bạc192 Huy hiệu Đồng18 gold badges173 silver badges192 bronze badges
Bối cảnh: Đối với loại công việc này, bạn nên sử dụng thư viện Python PETL tuyệt vời. Điều đó sẽ giúp bạn tiết kiệm rất nhiều công việc và sự thất vọng tiềm năng khi làm mọi việc 'theo cách thủ công' với mô -đun CSV tiêu chuẩn. Afaik, những người duy nhất vẫn sử dụng mô -đun CSV là những người chưa phát hiện ra các công cụ tốt hơn để làm việc với dữ liệu bảng [Pandas, PETL, v.v.], điều này là tốt, nhưng nếu bạn có kế hoạch làm việc với nhiều dữ liệu trong Sự nghiệp của bạn từ nhiều nguồn lạ khác nhau, học một cái gì đó như PETL là một trong những khoản đầu tư tốt nhất bạn có thể thực hiện. Để bắt đầu chỉ nên mất 30 phút sau khi bạn thực hiện PIP cài đặt PETL. Các tài liệu là tuyệt vời.
Trả lời: Giả sử bạn có bảng đầu tiên trong tệp CSV [bạn cũng có thể tải trực tiếp từ cơ sở dữ liệu bằng PETL]. Sau đó, bạn chỉ cần tải nó và làm như sau.
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
7
Đã trả lời ngày 29 tháng 5 năm 2015 lúc 12:19May 29, 2015 at 12:19
PeteBeatPetBeatPeteBeat
2714 Huy hiệu bạc11 Huy hiệu đồng4 silver badges11 bronze badges
Tôi nghĩ rằng có một cách dễ dàng hơn
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
8Vì vậy, ở đây
import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
5, import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
6 có nghĩa là tất cả các giá trị, import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
7 có nghĩa là vị trí của cột. Trong ví dụ dưới đây for row in reader:
content = list[row[i] for i in included_cols]
print content
7 sẽ được chọnID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
Đã trả lời ngày 13 tháng 2 năm 2020 lúc 11:38Feb 13, 2020 at 11:38
0
for row in reader:
content = list[row[i] for i in included_cols]
print content
0Đã trả lời ngày 30 tháng 5 năm 2019 lúc 16:58May 30, 2019 at 16:58
Hari Khari kHari K
2413 Huy hiệu bạc8 Huy hiệu đồng3 silver badges8 bronze badges
1
Nhờ cách bạn có thể lập chỉ mục và tập hợp một DataFrame của Gandas, một cách rất dễ dàng để trích xuất một cột từ tệp CSV vào một biến là:
for row in reader:
content = list[row[i] for i in included_cols]
print content
1Một vài điều cần xem xét:
Đoạn trích ở trên sẽ tạo ra một gấu trúc
import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
9 chứ không phải names = df.Names
0. Đề xuất từ Ayhan với import pandas as pd
df = pd.read_csv[csv_file]
saved_column = df.column_name #you can also use df['column_name']
4 cũng sẽ nhanh hơn nếu tốc độ là một vấn đề. Kiểm tra hai cách tiếp cận khác nhau bằng cách sử dụng names = df.Names
2 trên tệp CSV có kích thước 2122 KB mang lại names = df.Names
3 cho phương pháp USECOLS và names = df.Names
4 cho phương pháp được đề xuất của tôi.Và đừng quên
names = df.Names
5Đã trả lời ngày 10 tháng 12 năm 2018 lúc 8:33Dec 10, 2018 at 8:33
Vestlandvestlandvestland
48.3K34 Huy hiệu vàng162 Huy hiệu bạc266 Huy hiệu Đồng34 gold badges162 silver badges266 bronze badges
Nếu bạn cần xử lý các cột một cách riêng biệt, tôi muốn phá hủy các cột với mẫu
names = df.Names
6 ["giải nén" một cách hiệu quả]. Vì vậy, ví dụ của bạn:for row in reader:
content = list[row[i] for i in included_cols]
print content
2Đã trả lời ngày 15 tháng 1 năm 2019 lúc 18:59Jan 15, 2019 at 18:59
for row in reader:
content = list[row[i] for i in included_cols]
print content
3
7 là một loạt các cột, hãy sử dụng nó nếu bạn muốn đọc thêm một cột đónames = df.Names
8 là cột đơn, sử dụng nó để đọc một cộtnames = df.Names
9 lànames = df.Names
0import 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']]
TIỀN THƯỞNG
13K15 Huy hiệu vàng42 Huy hiệu bạc77 Huy hiệu đồng15 gold badges42 silver badges77 bronze badges
Đã trả lời ngày 20 tháng 11 năm 2021 lúc 11:21Nov 20, 2021 at 11:21
for row in reader:
content = list[row[i] for i in included_cols]
print content
4Đã trả lời ngày 22 tháng 10 năm 2020 lúc 15:10Oct 22, 2020 at 15:10
FredfredFred
1731 Huy hiệu bạc9 Huy hiệu đồng1 silver badge9 bronze badges
for row in reader:
content = list[row[i] for i in included_cols]
print content
5
Chris
119K89 Huy hiệu vàng263 Huy hiệu bạc244 Huy hiệu Đồng89 gold badges263 silver badges244 bronze badges
Đã trả lời ngày 19 tháng 8 lúc 5:00Aug 19 at 5:00
1
Để tìm nạp tên cột, thay vì sử dụng readlines [] sử dụng tốt hơn readline [] để tránh vòng lặp và đọc tệp hoàn chỉnh và lưu trữ nó trong mảng.column name, instead of using readlines[] better use readline[] to avoid loop & reading the complete file & storing it in the array.
for row in reader:
content = list[row[i] for i in included_cols]
print content
6Đã trả lời ngày 15 tháng 5 năm 2017 lúc 13:52May 15, 2017 at 13:52
SurensurenSuren
Phù hiệu bằng đồng 3777 bronze badges