簡體   English   中英

在python中對二維數組的一部分求和

[英]Summing part of 2D array in python

我有一個二維數組。 操作數組的 x 列后,我創建了一個新的二維數組 (data2),其中對 x 列進行了新的更改(y 列保持不變)。 我現在想將 data2 中的 y 值數組附加到一個新數組中,僅當其 x 值大於 3 或小於 5 時。例如,如果二維數組是 ([2,3], [4,5] , [3.5,6], [9,7]),我只想要新數組中的 y 值 5 和 6,因為它們的 x 值介於 3 和 5 之間。我被卡住了。 請幫忙!

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('blah.txt') #blah.txt is a 2d array

c = (3*10)^8

x = c /((data[:,0])*10)

y = data[:,1]


data2 = np.array((x,y)).T

def new_yarray(data2):

    yarray =[]

    if data2[:,0] <= 5 or data2[:,0] >= 3:

        np.append(data2[:,1])

    print yarray

    return yarray

為了清楚起見,這里有一個單行解決方案,分為幾個步驟。

給定一個數組

>>> a
array([[ 2. ,  3. ],
       [ 4. ,  5. ],
       [ 3.5,  6. ],
       [ 9. ,  7. ]])

您可以使用np.where()找到x值大於 3 且小於 5 的元素的索引

>>> np.where(np.logical_and(a[:,0] > 3,a[:,0] < 5))
(array([1, 2]),)

其中a[:,0] = array([ 2. , 4. , 3.5, 9. ])是所有x值的數組。 現在,您可以通過以下方式獲得所有對應的y值,其中3 < x < 5

>>> a[np.where(np.logical_and(a[:,0] > 3,a[:,0] < 5))][:,1]
array([ 5.,  6.])

您可以使用此函數來展平列表,然后根據其附加值。

def flatten_list(a, result=None):
    """ Flattens a nested list. """
    if result is None:
        result = []

    for x in a:
        if isinstance(x, list):
            flatten_list(x, result)
        else:
            result.append(x)
    return result

lst = ([2,3], [4,5], [3.5,6], [9,7])

lst = flatten_list(lst)

new_lst = []
for i in lst:
    if (float(i) > 3 and float(i) < 5):
        new_lst.append(i)
print new_lst

在這種情況下,只有 3.5 和 4 大於 3 且小於 5...

暫無
暫無

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

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