簡體   English   中英

Python Numpy Array索引

[英]Python Numpy Array indexing

我在Numpy索引方面遇到了一個小難題。 當它應該給出三個不同數組的索引(腳本中的F_fit)時,腳本只給出最后一個數組的索引三次。 我確信這是一件簡單的事情,但我還沒想到它。 3_phases.txt文件包含這3行

1  -1   -1  -1   1   1
1   1    1  -1   1   1
1   1   -1  -1  -1   1

這是代碼:

import numpy as np
import matplotlib.pyplot as plt

D = 12.96
n = np.arange(1,7)

F0 = 1.0
x = np.linspace(0.001,4,2000)
Q = 2*np.pi*np.array([1/D, 2/D, 3/D, 4/D, 5/D, 6/D])
I = (11.159, 43.857, 26.302, 2.047, 0.513, 0.998)    
phase = np.genfromtxt('3_phases.txt')

for row in phase:

    F = (np.sqrt(np.square(n)*I/sum(I)))*row
    d = sum(i*(np.sin(x*D/2+np.pi*j)/(x*D/2+np.pi*j))for i,j in zip(F,n))
    e = sum(i*(np.sin(x*D/2-np.pi*j)/(x*D/2-np.pi*j))for i,j in zip(F,n))
    f_0 = F0*(np.sin(x*D/2)/(x*D/2))
    F_cont = np.array(d) + np.array(e) + np.array(f_0)
    plt.plot(x,F_cont,'r')
    #plt.show()
    plt.clf()

D2 = 12.3
I2 = (9.4, 38.6, 8.4, 3.25, 0, 0.37)
Q2 = 2*np.pi*np.array([1/D2, 2/D2, 3/D2, 4/D2, 5/D2, 6/D2])
n2 = np.arange(1,7)

for row in phase:
    F2 = (np.sqrt(np.square(n2)*I2/sum(I2)))*row
    plt.plot(Q2,F2,'o')
    #plt.show()
    F_data = F2
    Q_data = Q2
    I_data = np.around(2000*Q2/(4-0.001))
    I_data = np.array(map(int,I_data))
    F_fit = F_cont[I_data]
    print F_fit
    R2 = (1-(sum(np.square(F_data-F_fit))/sum(np.square(F_data-np.mean(F_data)))))

任何幫助,將不勝感激。

每次進行第一次循環時,您都在重新定義F_cont 當您進入第二個循環(包含所有_2值)時,您只能訪問最后rowF_cont

要解決此問題,請將_2定義移到第一個循環之上,然后只進行一次循環,然后您就可以訪問每個F_cont並且您的打印輸出會有所不同。

以下代碼與您的相同,除了上面描述的重新排列,以及我從上面實現我的評論(在Q使用n/D )的事實。

import numpy as np
import matplotlib.pyplot as plt

D = 12.96
n = np.arange(1,7)

F0 = 1.0
x = np.linspace(0.001,4,2000)
Q = 2*np.pi*n/D
I = (11.159, 43.857, 26.302, 2.047, 0.513, 0.998)    
phase = np.genfromtxt('3_phases.txt')

D2 = 12.3
I2 = (9.4, 38.6, 8.4, 3.25, 0, 0.37)
Q2 = 2*np.pi*n/D2
n2 = np.arange(1,7)

for row in phase:

    F = (np.sqrt(np.square(n)*I/sum(I)))*row
    d = sum(i*(np.sin(x*D/2+np.pi*j)/(x*D/2+np.pi*j))for i,j in zip(F,n))
    e = sum(i*(np.sin(x*D/2-np.pi*j)/(x*D/2-np.pi*j))for i,j in zip(F,n))
    f_0 = F0*(np.sin(x*D/2)/(x*D/2))
    F_cont = np.array(d) + np.array(e) + np.array(f_0)
    plt.plot(x,F_cont,'r')
    plt.clf()

    F2 = (np.sqrt(np.square(n2)*I2/sum(I2)))*row
    plt.plot(Q2,F2,'o')
    F_data = F2
    Q_data = Q2
    I_data = np.around(2000*Q2/(4-0.001))
    I_data = np.array(map(int,I_data))
    F_fit = F_cont[I_data]
    print F_fit
    R2 = (1-(sum(np.square(F_data-F_fit))/sum(np.square(F_data-np.mean(F_data)))))

F_fit正在從I_data計算,而I_data又是從Q2計算的。 Q2在循環外部設置,並且不依賴於row - 也許你的意思是I_dataF2的函數而不是?

暫無
暫無

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

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