Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?


Để trích xuất tệp CSV cho các cột cụ thể để liệt kê trong Python, chúng ta có thể sử dụng phương thức pandas read_csv ().read_csv() method.

Các bước

  • Tạo một danh sách các cột phải được trích xuất.

  • Sử dụng phương thức read_csv () để trích xuất tệp CSV vào khung dữ liệu.read_csv() method to extract the csv file into data frame.

  • In dữ liệu bị xáo trộn.

  • Biểu thị khung dữ liệu bằng phương thức & nbsp; Plot (). plot() method.

  • Để hiển thị hình, sử dụng & nbsp; show () & nbsp; phương thức. show() method.

Thí dụ

import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:
", df) plt.plot(df.Name, df.Marks) plt.show()

Tệp CSV chứa dữ liệu sau -

TênĐiểm
Arun98
Shyam75
Chính phủ54
Javed92
Raju87

Đầu ra

Khi chúng tôi thực thi mã, nó sẽ trích xuất dữ liệu từ tệp CSV và hiển thị biểu đồ sau -

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

Cập nhật vào ngày 07-tháng 5 năm 2021 07:45:13

  • Câu hỏi và câu trả lời liên quan
  • Làm thế nào để đọc tệp CSV trong Python?
  • Python Pandas- Tạo nhiều tệp CSV từ tệp CSV hiện có
  • Làm thế nào để sắp xếp CSV theo nhiều cột trong Python?
  • Làm thế nào để lưu một từ điển Python vào tệp CSV?
  • Đọc và viết tệp CSV bằng Python
  • Làm thế nào để trích xuất tiện ích mở rộng tệp bằng Python?
  • Chiết xuất Python Khóa cụ thể từ từ điển?
  • Python - Cách viết Pandas DataFrame vào tệp CSV
  • Làm thế nào để nhập tệp CSV trong PHP?
  • Python - Đọc tệp CSV với gấu trúc không có tiêu đề?
  • Làm thế nào để trích xuất các cột khung dữ liệu được lưu trữ trong một danh sách trong r?
  • Làm thế nào để chuyển đổi tệp JSON sang tệp CSV bằng PowerShell?
  • Nhập / Xuất tệp CSV trong PowerShell
  • Viết dữ liệu từ cơ sở dữ liệu vào tệp .csv
  • Viết một tệp dữ liệu gấu trúc vào tệp CSV

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ử

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
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
9,
for row in reader:
    content = list(row[i] for i in included_cols)
print content
0 và
for row in reader:
    content = list(row[i] for i in included_cols)
print content
1.

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:

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
9 sẽ tương ứng với
for row in reader:
    content = list(row[i] for i in included_cols)
print content
3 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
4 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.

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

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
5 của mình.in your
for row in reader:
    content = list(row[i] for i in included_cols)
print content
5 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
6 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
5 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:

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

Để thay đổi DELIMINATOR Thêm

for row in reader:
    content = list(row[i] for i in included_cols)
print content
8 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
9

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

HennyhhennyhHennyH

7.6542 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:

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

Loại bỏ các cột không cần thiết tại thời điểm phân tích:

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

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

VasilinovikovvasilinovikovVasiliNovikov

9.1003 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
0. Ví dụ: nếu đây là cơ sở dữ liệu của bạn
for row in reader:
        content = list(row[i] for i in included_cols)
        print content
1:

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

Và bạn muốn cột

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
9:

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

Dễ dàng hơn bạn có thể sử dụng

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

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

Đã 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

for row in reader:
        content = list(row[i] for i in included_cols)
        print content
4 với tham số
for row in reader:
        content = list(row[i] for i in included_cols)
        print content
5:

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

Example:

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

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

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

Đã 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

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

Vì vậy, ở đây

for row in reader:
        content = list(row[i] for i in included_cols)
        print content
6,
for row in reader:
        content = list(row[i] for i in included_cols)
        print content
7 có nghĩa là tất cả các giá trị,
for row in reader:
        content = list(row[i] for i in included_cols)
        print content
8 có nghĩa là vị trí của cột. Trong ví dụ dưới đây
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
8 sẽ được chọn

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

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
1

Đã 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à:

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
2

Mộ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']
0 chứ không phải
import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']
1. Đề xuất từ ​​Ayhan với
for row in reader:
        content = list(row[i] for i in included_cols)
        print content
5 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
import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']
3 trên tệp CSV có kích thước 2122 KB mang lại
import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']
4 cho phương pháp USECOLS và
import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']
5 cho phương pháp được đề xuất của tôi.

Và đừng quên

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

Đã trả lời ngày 10 tháng 12 năm 2018 lúc 8:33Dec 10, 2018 at 8:33

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

Vestlandvestlandvestland

48.4K34 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

import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']
7 ("giải nén" một cách hiệu quả). Vì vậy, ví dụ của bạ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
3

Đã trả lời ngày 15 tháng 1 năm 2019 lúc 18:59Jan 15, 2019 at 18:59

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
  • import pandas as pd
    df = pd.read_csv(csv_file)
    saved_column = df.column_name #you can also use df['column_name']
    
    8 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
  • import pandas as pd
    df = pd.read_csv(csv_file)
    saved_column = df.column_name #you can also use df['column_name']
    
    9 là cột đơn, sử dụng nó để đọc một cột
  • names = df.Names
    
    0 là
    names = df.Names
    
    1

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

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
5

Đã 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

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

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

Chris

119K89 Huy hiệu vàng264 Huy hiệu bạc245 Huy hiệu Đồng89 gold badges264 silver badges245 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.

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 15 tháng 5 năm 2017 lúc 13:52May 15, 2017 at 13:52

Hướng dẫn how do i extract a column from a csv file in python? - làm cách nào để trích xuất một cột từ tệp csv trong python?

SurensurenSuren

Phù hiệu bằng đồng 3777 bronze badges

Làm cách nào để trích xuất một cột cụ thể trong Python?

Làm cách nào để trích xuất một cột cụ thể từ một khung dữ liệu trong Python ?..
Cú pháp: biến_name = dataFrame_name [Row (s), cột (s)].
Ví dụ 1: A = DF [C (1,2), C (1,2)].
Giải thích: Nếu chúng ta muốn trích xuất nhiều hàng và cột, chúng ta có thể sử dụng c () với tên hàng và tên cột làm tham số ..

Làm thế nào để bạn truy cập một cột trong tệp CSV trong Python?

Python3. Trong phương thức này, chúng tôi sẽ nhập thư viện CSV và mở tệp ở chế độ đọc, sau đó chúng tôi sẽ sử dụng hàm dictreader () để đọc dữ liệu của tệp CSV. Hàm này giống như một người đọc thông thường, nhưng nó ánh xạ thông tin đến một từ điển có các khóa được đưa ra bởi các tên cột và tất cả các giá trị dưới dạng các khóa.import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys.

Làm cách nào để nhận các cột trong tệp CSV?

Làm cách nào để đặt văn bản vào các cột riêng biệt trong tệp CSV trong .....
Chọn cột đầu tiên (cột A).
Nhấp vào 'Dữ liệu' và sau đó trên 'Văn bản vào các cột'.
Tùy chọn 'phân định' đã được chọn trước. Đây là tùy chọn chính xác. Nhấp vào 'Tiếp theo' ..
Chọn tùy chọn 'Dấu phẩy' và nhấp vào 'Kết thúc' ..

Làm cách nào để trích xuất dữ liệu từ tệp CSV trong Python?

Đọc CSV bằng mô -đun sẵn có của Python có tên CSV bằng CSV ...
Nhập thư viện CSV.Nhập CSV ..
Mở tệp CSV.Các .....
Sử dụng đối tượng CSV.Reader để đọc tệp CSV.csvreader = csv.Reader (tệp).
Trích xuất tên trường.Tạo một danh sách trống gọi là tiêu đề.....
Trích xuất các hàng/hồ sơ.....
Đóng tệp ..