[英]Numerical operations on arrays while reading from CSV file
我試圖在從 CSV 文件中讀取一些值的同時對幾個數組進行一些數值運算。
我有一個固定的接收器坐標,我從跟蹤太陽的 CSV 文件中讀取定日鏡的坐標。
接收器坐標:
# co-ordinates of Receiver
XT = 0 # X co-ordinate of Receiver
YT = 0 # Y co-ordinate of Receiver
ZT = 207.724 # Z co-ordinate of Receiver, this is the height of tower
A = np.array(([XT],[YT],[ZT]))
print(A," are the co-ordinates of the target i.e. the receiver")
十個定日鏡的坐標:我從帶有以下數據的 CSV 文件中讀取的數據:
#X,Y,Z
#-1269.56,-1359.2,5.7
#1521.28,-68.0507,5.7
#-13.6163,1220.79,5.7
#-1388.76,547.708,5.7
#1551.75,-82.2342,5.7
#405.92,-1853.83,5.7
#1473.43,-881.703,5.7
#1291.73,478.988,5.7
#539.027,1095.43,5.7
#-1648.13,-73.7251,5.7
我讀取 CSV 的坐標如下:
import csv
# Reading data from csv file
with open('Heliostat Field Layout Large heliostat.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
X = []
Y = []
Z = []
for row in readCSV:
X_coordinates = row[0]
Y_coordinates = row[1]
Z_coordinates = row[2]
X.append(X_coordinates)
Y.append(Y_coordinates)
Z.append(Z_coordinates)
Xcoordinate = [float(X[c]) for c in range(1,len(X))]
Ycoordinate=[float(Y[c]) for c in range(1,len(Y))]
Zcoordinate=[float(Z[c]) for c in range(1,len(Z))]
現在,當我嘗試打印十個定日鏡的坐標時,我得到了三個大陣列,其中所有 Xcoordinate、Ycoordinate 和 Zcoordinate 被分組為一個而不是十個不同的輸出。
[[[-1269.56 1521.28 -13.6163 -1388.76 1551.75 405.92 1473.43
1291.73 539.027 -1648.13 ]]
[[-1359.2 -68.0507 1220.79 547.708 -82.2342 -1853.83
-881.703 478.988 1095.43 -73.7251]]
[[ 5.7 5.7 5.7 5.7 5.7 5.7 5.7
5.7 5.7 5.7 ]]] are the co-ordinates of the heliostats
我用了:
B = np.array(([Xcoordinate],[Ycoordinate],[Zcoordinate]))
print(B," are the co-ordinates of the heliostats")
什么是錯誤?
此外,我想有一個我喜歡 B - A 的數組,我使用它:
#T1 = matrix(A)- matrix(B)
#print(T1," is the target vector for heliostat 1, T1")
我應該如何對數組 A 和 B 進行數值運算? 我在這里嘗試了矩陣運算。 錯了嗎?
你的代碼是正確的
以下輸出是 numpy 數組的顯示方式。
[[-1359.2 -68.0507 1220.79 547.708 -82.2342 -1853.83 -881.703 478.988 1095.43 -73.7251]]
盡管存在這些值粘在一起的錯覺,但它們在數組中是完全不同的。 您可以訪問單個值
print(B[1, 0, 0]) # print Y[0]
您要執行的數組 A 和 B 的減法將起作用
T1 = np.matrix(A)- np.matrix(B)
print(T1," is the target vector for heliostat 1, T1")
我可以提兩個建議嗎?
您可以使用 numpy 的函數 loadtxt 讀取在文本文件中寫為矩陣的 numpy 數組(這里就是這種情況):
your_file = 'Heliostat Field Layout Large heliostat.csv' B = np.loadtxt(your_file, delimiter=',', skiprows=1)
結果將是一個 (3, 10) numpy 數組。
您可以直接對 numpy 數組執行廣播操作(因此您無需將其轉換為矩陣)。 您只需要注意尺寸。
在您的原始腳本中,您只需要編寫:
T1 = A - B
如果按照建議使用 loadtxt 獲取數組 B,您將得到一個 (10, 3) 數組,而 A 是一個 (3, 1) 數組。 數組 B 必須首先在 (3, 10) 數組中重新整形:
B = B.reshape((3, 10)) T1 = A - B
編輯:計算 T1 的每個 3D 向量的范數
norm_T1 = np.sqrt( np.sum( np.array(T1)**2, axis=0 ) )
請注意,在您的代碼中 T1 是一個矩陣,所以 T1**2 是一個矩陣乘積。 為了計算 T1 的每個向量 v 的 sqrt( v[0]**2 + v[1]**2 + v[2]**2 ),我首先將其轉換為一個 numpy 數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.