我需要用字典元素填充数组。例如:
a = np.empty(2,2)
我需要以这种方式填写(不允许)
for i in range(2):
for j in range(2):
a[i,j] = {'x': b[i], 'y': c[j]}
其中b
和c
是数据框的其他列表/数组或列。
答案 0 :(得分:1)
import numpy as np
a = np.zeros((2, 2))
b = np.ones(a.shape[0])
c = np.ones(a.shape[1]) * [2]
list_a = a.tolist()
for i in range(2):
for j in range(2):
list_a[i][j] = {'x': b[i], 'y': c[j]}
a = np.array(list_a)
print(a)
输出:
array([[{'x': 1.0, 'y': 2.0}, {'x': 1.0, 'y': 2.0}],
[{'x': 1.0, 'y': 2.0}, {'x': 1.0, 'y': 2.0}]], dtype=object)
答案 1 :(得分:1)
如果创建对象dtype数组,则可以在插槽中放置任何内容:
In [9]: a = np.empty((2,2), object)
In [10]: a
Out[10]:
array([[None, None], # empty() fills with None
[None, None]], dtype=object)
In [11]: for i in range(2):
...: for j in range(2):
...: a[i,j] = {'x':b[i], 'y':c[j]}
...:
In [12]: a
Out[12]:
array([[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}],
[{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]], dtype=object)
但是列表理解同样有效
In [13]: [[{'x':b[i],'y':c[j]} for j in range(2)] for i in range(2)]
Out[13]: [[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}], [{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]]
In [14]: np.array(_)
Out[14]:
array([[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}],
[{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]], dtype=object)
或者您可以从平面列表开始,然后重新排列数组的形状:
In [15]: [{'x':b[i],'y':c[j]} for j in range(2) for i in range(2)]
Out[15]: [{'x': 1, 'y': 4}, {'x': 3, 'y': 4}, {'x': 1, 'y': 3}, {'x': 3, 'y': 3}]
In [16]: np.array(_)
Out[16]:
array([{'x': 1, 'y': 4}, {'x': 3, 'y': 4}, {'x': 1, 'y': 3},
{'x': 3, 'y': 3}], dtype=object)
In [18]: _.reshape(2,2)
Out[18]:
array([[{'x': 1, 'y': 4}, {'x': 3, 'y': 4}],
[{'x': 1, 'y': 3}, {'x': 3, 'y': 3}]], dtype=object)
使用该词典列表将比列表更容易或更快捷。
或者,我们可以创建带有2个命名字段的结构化数组。从元组列表开始:
In [19]: [(b[i],c[j]) for j in range(2) for i in range(2)]
Out[19]: [(1, 4), (3, 4), (1, 3), (3, 3)]
In [20]: np.array(_, dtype=[('x',int),('y',int)])
Out[20]: array([(1, 4), (3, 4), (1, 3), (3, 3)], dtype=[('x', '<i8'), ('y', '<i8')])
In [21]: _.reshape(2,2)
Out[21]:
array([[(1, 4), (3, 4)],
[(1, 3), (3, 3)]], dtype=[('x', '<i8'), ('y', '<i8')])
In [22]: _['x']
Out[22]:
array([[1, 3],
[1, 3]])
相反,要从2d对象数组中获取所有x
值:
In [24]: [i['x'] for i in a.flat]
Out[24]: [1, 1, 3, 3]