[英]How to assign each row in a numpy array into keys in dictionary python
I have a rather large numpy array.我有一个相当大的 numpy 阵列。 I'd like to take each row in my array and assign it to be a key in a dictionary I created.我想获取数组中的每一行并将其分配为我创建的字典中的一个键。 For example, I have a short 2-dimensional array:例如,我有一个短的二维数组:
my_array = [[5.8 2.7 3.9 1.2]
[5.6 3. 4.5 1.5]
[5.6 3. 4.1 1.3]]
and I'd like to create a dictionary that each row is a key, with empty values (later I plan to add values dynamically), like so:我想创建一个字典,每行都是一个键,具有空值(稍后我计划动态添加值),如下所示:
my_dict = {[5.8 2.7 3.9 1.2]:,
[5.6 3. 4.5 1.5]:,
[5.6 3. 4.1 1.3]:}
How can I do it?我该怎么做?
You'll have to put some placeholder for the values, None
is often used to mean nothing.您必须为这些值放置一些占位符, None
通常用来表示没有任何意义。 You also need to convert the rows to something hashable;您还需要将行转换为可散列的东西; tuple
s are the obvious choice. tuple
是显而易见的选择。
my_array = np.arange(15).reshape(3,5)
import numpy.lib.recfunctions as nlr
dict.fromkeys(nlr.unstructured_to_structured(my_array).tolist())
# {(0, 1, 2, 3, 4): None, (5, 6, 7, 8, 9): None, (10, 11, 12, 13, 14): None}
unstructured_to_structured
is a little trick that lumps each row of my_array
together using a compund dtype
. unstructured_to_structured
是一个小技巧,它使用复合dtype
将my_array
的每一行集中在一起。 tolist
converts these compound elements to tuples. tolist
将这些复合元素转换为元组。
If you would prefer a different placeholder instead of None
you can specify that as the second argument to dict.fromkeys
.如果您希望使用不同的占位符而不是None
,您可以将其指定为dict.fromkeys
的第二个参数。 (Do not use a mutable placeholder because all the values will be references to the same object.) (不要使用可变占位符,因为所有值都将引用相同的 object。)
If a tuple will do, then:如果一个元组可以,那么:
import numpy as np
my_array = np.array([[5.8, 2.7, 3.9, 1.2],
[5.6, 3., 4.5, 1.5],
[5.6, 3., 4.1, 1.3]])
d = { k : None for k in map(tuple, my_array)}
print(d)
Output Output
{(5.8, 2.7, 3.9, 1.2): None, (5.6, 3.0, 4.5, 1.5): None, (5.6, 3.0, 4.1, 1.3): None}
As an alternative, you could do:作为替代方案,您可以这样做:
d = { tuple(row) : None for row in my_array}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.