簡體   English   中英

在Python中,讀取帶有數據列的csv文件,並根據列標題分配變量

[英]In Python, read in csv file with columns of data and assign variables according to the column headers

我正在處理類似於以下('testcsv.csv')的CSV文件:

x, y, z
1, 2, 3
4, 5, 6

也就是說,第一列包含帶有變量名稱的標題,隨后的列包含表示與這些變量相對應的數組的數值。 我想將變量讀入我的“工作區”(使用Matlab術語),使得“ x”是數組[1,4],“ y”是數組[2,5],而“ z”是數組[3,6]。 以下腳本可實現此目的:

import numpy as np

filename='testcsv.csv'
# Read column headers (to be variable naames)
with open(filename) as f:
     firstline = f.readline()                    # Read first line of csv
     firstline = firstline.replace("\n","")      # Remove new line characters
     firstline = firstline.replace(" ","")       # Remove spaces
     ColumnHeaders = firstline.split(",")        # Get array of column headers

# Read in the data (omitting the first row containing column headers)
data=np.loadtxt(filename,skiprows=1,delimiter=",")

# Assign the data to arrays, with names of the variables generated from column headers
Ind=0
for Var in ColumnHeaders:
    vars()[Var]=data[:,Ind]         # Assign the columns of the data to variables names after the column headers
    Ind=Ind+1

唯一的問題是我想使它成為一個函數,該函數以“文件名”作為輸入並全局寫出變量。 我知道“全局”函數,但是由於變量名是動態獲取的,因此我不確定如何使用它。 有任何想法嗎?

遵循Kevin的建議,我只是將“ vars()”替換為“ globals()”。 這是新的腳本:

import numpy as np

filename='testcsv.csv'

def read_csv(filename):

# Read column headers (to be variable naames)
with open(filename) as f:
     firstline = f.readline()                    # Read first line of csv
     firstline = firstline.replace("\n","")      # Remove new line characters
     firstline = firstline.replace(" ","")       # Remove spaces
     ColumnHeaders = firstline.split(",")        # Get array of column headers

# Read in the data (omitting the first row containing column headers)
data=np.loadtxt(filename,skiprows=1,delimiter=",")

# Assign the data to arrays, with names of the variables generated from column headers
Ind=0
for Var in ColumnHeaders:
    globals()[Var]=data[:,Ind]         # Assign the columns of the data to variables names after the column headers
    Ind=Ind+1

read_csv(filename)

(“ def”中的行也應縮進,但此復制粘貼未捕獲到該行)。 腳本現在根據需要使用函數“ read_csv”。

暫無
暫無

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

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