簡體   English   中英

如何將 CSV 文件的列導出為 python 中的 arrays?

[英]how to export a columns of CSV file as an arrays in python?

我有一個包含 2 列的 CSV 文件,我想將這 2 列導出為 2 arrays。 如何使用 Python 完成它?

您可以通過這種方式使用列表理解和循環通過 csv 文件:

import csv 

with open('example.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    column1 = [row[0] for row in csv_reader]
    column2 = [row[0] for row in csv_reader]

我會使用 pandas 以獲得更好的性能和未來的操作

import pandas

df = pandas.read_csv("example.csv")

for row in df.iterrows():
    print(row)

您可以使用 pandas 並指定列名來執行此操作。

import pandas as pd
df=pd.read_csv("example.csv")
        
array1=df["col_name1"].values # as numpy array
array2=list(df["col_name2"].values) # as python array

csv.reader返回的行的迭代使用zip將數據組裝成列:

import csv
with open('example.csv') as f:
    reader = csv.reader(f)
    columns_as_lists = [list(c) for c in zip(*reader)]
print(columns_as_lists[0])  # All the values in the first column of your CSV
print(columns_as_lists[1])  # All the values in the second column of your CSV

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM