簡體   English   中英

如何在python中使用條件有效地選擇特定列

[英]How to efficiently select specific columns with condition in python

例如,我有以下2d數組:

ls = [
    [1,2,3,4,'A',5],
    [1,2,3,4,'A',5],
    [1,2,3,4,'A',5],
    [-1,-2,-3,-4,'B',-5],
    [-1,-2,-3,-4,'B',-5],
    [-1,-2,-3,-4,'B',-5]
]

我想選擇ls的第一,第三,第四列,並將每一列分別保存到一個新列表中。 此外,我希望選擇第5列的條件,即檢查'A'還是'B' ,如下所示:

la1 = [int(x[0]) for x in ls if 'A' in x[4]]
la2 = [int(x[2]) for x in ls if 'A' in x[4]]
la3 = [float(x[3]) for x in ls if 'A' in x[4]]
lb1 = [int(x[0]) for x in ls if 'B' in x[4]]
lb2 = [int(x[2]) for x in ls if 'B' in x[4]]
lb3 = [float(x[3]) for x in ls if 'B' in x[4]]

我知道我的實現在大型陣列中效率不高。 有沒有更好的實現方法? 謝謝大家的幫助!!!

您可以將6個列表理解合並為兩個:

la1, la2, la3= zip(*((x[0], x[2], float(x[3])) for x in ls if 'A' in x[4]))
lb1, lb2, lb3= zip(*((x[0], x[2], float(x[3])) for x in ls if 'B' in x[4]))

這首先創建一個三元組的列表(x[0], x[2], float(x[3])) ,然后使用舊的zip(*values)技巧對其進行轉置並將其解壓縮到la1, la2, la3變量。


比這更有效的是一個簡單的循環:

la1, la2, la3 = [], [], []
lb1, lb2, lb3 = [], [], []
for x in ls:
    if 'A' in x[4]:
        la1.append(x[0])
        la2.append(x[2])
        la3.append(float(x[3]))
    if 'B' in x[4]:
        lb1.append(x[0])
        lb2.append(x[2])
        lb3.append(float(x[3]))

您可以嘗試使用numpy ,它是python的高效數組庫:

import numpy as np

ls = np.array([  # wrap ls into numpy array
    [1,2,3,4,'A',5],
    [1,2,3,4,'A',5],
    [1,2,3,4,'A',5],
    [-1,-2,-3,-4,'B',-5],
    [-1,-2,-3,-4,'B',-5],
    [-1,-2,-3,-4,'B',-5]
])

a_rows = ls[:,4] == 'A' # select rows with A in 4-th column
b_rows = ls[:,4] == 'B'
col_1 = ls[:,0]  # select first column
col_3 = ls[:,2]
col_4 = ls[:,3]
la1 = col_1[a_rows]  # first column with respect to the rows with A
la2 = col_3[a_rows]
la3 = col_4[a_rows]
lb1 = col_1[b_rows]
lb2 = col_3[b_rows]
lb3 = col_4[b_rows]

我認為如果您有很多列表,將列表存儲在字典中將是明智的選擇,因為您根據某種條件拆分數據,所以for循環可能會更快:

d = {'la1': [],
     'la3': [],
     'la4': [],
     'lb1': [],
     'lb3': [],
     'lb4': []}

ls = [[1,2,3,4,'A',5],
      [1,2,3,4,'A',5],
      [1,2,3,4,'A',5],
      [-1,-2,-3,-4,'B',-5],
      [-1,-2,-3,-4,'B',-5],
      [-1,-2,-3,-4,'B',-5]]

for sublist in ls:
    if sublist[4] == "A":
        d['la1'].append(int(sublist[0]))
        d['la3'].append(int(sublist[2]))
        d['la4'].append(float(sublist[3]))
    elif sublist[4] == "B":
        d['lb1'].append(int(sublist[0]))
        d['lb3'].append(int(sublist[2]))
        d['lb4'].append(float(sublist[3]))

print (d)

#{'lb4': [-4.0, -4.0, -4.0], 'lb1': [-1, -1, -1], 'la3': [3, 3, 3], 'la4': [4.0, 4.0, 4.0], 'la1': [1, 1, 1], 'lb3': [-3, -3, -3]}

使用numpy數組它們比普通列表要快嘗試運行下面提供的代碼的每一行

ls = np.array([[1,2,3,4,'A',5],[1,2,3,4,'A',5],[1,2,3,4,'A',5],[-1,-2,-3,-4,'B',-5],[-1,-2,-3,-4,'B',-5],[-1,-2,-3,-4,'B',-5]])
filterA = (ls[:,4]=='A')
filterB = (ls[:,4]=='B')
newarrayA=ls[filterA]
newarrayB=ls[filterB]
selectedcolumnsA=newarrayA[:,(0,2,3)]
selectedcolumnsB=newarrayB[:,(0,2,3)]  
la1,la2,la3=selectedcolumnsA[:,0],selectedcolumnsA[:,1],selectedcolumnsA[:,2]
lb1,lb2,lb3=selectedcolumnsB[:,0],selectedcolumnsB[:,1],selectedcolumnsB[:,2]

希望對您有所幫助。如果您對此感到不舒服,請嘗試學習numpy。它一定會在將來對您有所幫助。

暫無
暫無

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

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