![](/img/trans.png)
[英]Remove subarray from a 2d array based on their existence in another 2d array (return a new 2d array)
[英]Separating a 2D array based on the first item in each subarray
我有一個長的 2D numpy 數組,如下所示:
[['State1' 15]
['State1' 19]
['State1' 26]
['State2' 3]
['State1' 9]
...
['State2' 3]]
其中只有 2 個狀態可能作為第一個元素。 我想將這個二維數組分成兩個不同的數組,每個州一個,每個州只有數字信息(我需要這個用於箱線圖),但我不太確定如何分開。 我試過列表理解,但它返回一長串 True 和 Falses 而不是值本身
st1 = [state[0] == "State1" for state in joined] #joined is the array shown above
我怎么能用更簡潔的方式做到這一點?
編輯:
我的filter()
問題是它返回數組,我不知道如何指定只返回第二個條目:
normal = list(filter(lambda x: x[0] == "State1", joined))
[array(['State1', '14.4659'], dtype='<U9'), array(['State1', '20.8356'], dtype='<U9'), array(['State1', '5.3358'], dtype='<U9'), array(['State1', '1.9017'],...]
這是使用defaultdict
的一種方法:
from collections import defaultdict
my_list = [['State1', 15], ['State1', 19], ['State1', 26], ['State1', 3],
['State2', 9], ['State2', 3]]
d = defaultdict(list)
for l in my_list:
d[l[0]].append(l)
print(list(d.values()))
[[['State1', 15], ['State1', 19], ['State1', 26], ['State1', 3]],
[['State2', 9], ['State2', 3]]]
我實際上找到了另一種使用numpy
的方法,如下所示:
index = np.where(joined[0:,] == "State1")[0] #get indices where this is true, returns the array
normals = joined[index][:,1] #to get an array of second elements
我不清楚你是在使用數組還是列表,但是假設你想從列表中的列表中拆分值,你可以像 Python 一樣簡單:你可以讀取遍歷每個列表位置的值。 在此解決方案中,無需導入任何內容即可解決您的挑戰:
假設您的數據沒有任何值超過“State1”和“State2”
#Creating your list
l = [['State1', 11], ['State2', 13], ['State1', 2], ['State2', 5], ['State1', 7], ['State1', 3]]
用 Python 解決
#Creating a empty lists for saving separated values
states=[]
values=[]
#Reading states & values from your data
for x in range(len(l)):
stat=l[x][0]
val=l[x][1]
states.append(stat)
values.append(val)
#Showing the data contained in each list: states & values
print(states)
print(values)
輸出
#First list
['State1', 'State2', 'State1', 'State2', 'State1', 'State1']
#Second list
[11, 13, 2, 5, 7, 3]
如果您想使用上面描述的 True/False 值從其中一個州過濾列表,請嘗試以下操作:
from itertools import compress
bool_list=[l[state][0]=='State1' for state in range(len(l))]
st1=list(compress(l, bool_list))
print(st1)
輸出
#Filtered data by State1
[['State1', 11], ['State1', 2], ['State1', 7], ['State1', 3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.