1

これは私の初めての投稿です。私は少しPythonを学ぼうとしています。Python 3 と numpy を使用します。

いくつかのチュートリアルを行った後、飛び込んで、仕事で役立つかもしれない小さなプロジェクトを試すことにしました。これは私にとって良い学習方法です。

数行のヘッダーを持つ CSV ファイルからデータを読み取るプログラムを作成しました。次に、ヘッダー名に基づいてそのファイルから特定の列を抽出し、それを特定の形式の新しい csv ファイルに出力します。 .

私が持っているプログラムは正常に動作し、私が望むことを行いますが、私は初心者なので、コードを改善する方法についていくつかのヒントが必要です.

私のメイン データ ファイル (csv) は、長さ約 57 列、深さ約 36 行なので、大きくありません。

正常に動作しますが、アドバイスと改善を探しています。

import csv
import numpy as np

#make some arrays..at least I think thats what this does
A=[]
B=[]
keep_headers=[]

#open the main data csv file 'map.csv'...need to check what 'r' means
input_file = open('map.csv','r')

#read the contents of the file into 'data'
data=csv.reader(input_file, delimiter=',')

#skip the first 2 header rows as they are junk
next(data)
next(data)

#read in the next line as the 'header'
headers = next(data)

#Now read in the numeric data (float) from the main csv file 'map.csv'
A=np.genfromtxt('map.csv',delimiter=',',dtype='float',skiprows=5)

#Get the length of a column in A
Alen=len(A[:,0])

#now read the column header values I want to keep from 'keepheader.csv'
keep_headers=np.genfromtxt('keepheader.csv',delimiter=',',dtype='unicode_')

#Get the length of keep headers....i.e. how many headers I'm keeping. 
head_len=len(keep_headers)

#Now loop round extracting all the columns with the keep header titles and
#append them to array B
i=0
while i < head_len:
    #use index to find the apprpriate column number. 
    item_num=headers.index(keep_headers[i])
    i=i+1

    #append the selected column to array B
    B=np.append(B,A[:,item_num])

#now reshape the B array 
B=np.reshape(B,(head_len,36))

#now transpose it as thats the format I want. 
B=np.transpose(B)

#save the array B back to a new csv file called 'cmap.csv'
np.savetxt('cmap.csv',B,fmt='%.3f',delimiter=",") 

ありがとう。

4

1 に答える 1