Converting a list of ints, tuples into an numpy array

╄→尐↘猪︶ㄣ 提交于 2019-12-20 05:50:54

问题


I have a list of [float, (float,float,float..) ] ... Which is basically an n-dimensional point along with a fitness value for each point. For eg.

4.3, (2,3,4)
3.2, (1,3,5)
.
.
48.2, (23,1,32)

I wish to randomly sample one point based upon the fitness values. I decided the best way to do this would be to use numpy.random.choice(range(n), 1, plist[:,:1,:1])

However, i need to convert this into an numpy array, for which i tried

>> pArr = np.array( plist ) 
ValueError: setting an array element with a sequence

I got the same error for np.asarray(plist) as well.. any suggestions??


回答1:


The following should work:

A = np.array([tuple(i) for i in initial_list],dtype=[('fitness',float),('point',(float,3))])

with initial_list = [[4.3, (2, 3, 4)], [3.2, (1, 3, 5)], ...]. Note that we need to transform each item of initial_list into a tuple for that trick to work, else NumPy cannot recognize the structure.

Your fitness entries are now accessible as A['fitness'], with the corresponding points as A['point']. If you select a list of actual fitness entries, indices, the corresponding points are given by A['point'][indices], which is a simple (n,3) array.




回答2:


Your question is difficult to understand. Is this what you're trying to do?

>>> x
[[4.3, (2, 3, 4)], [3.2, (1, 3, 5)], [48.2, (23, 1, 32)]]
>>> np.array([(a, b, c, d) for a, (b, c, d) in x])
array([[  4.3,   2. ,   3. ,   4. ],
       [  3.2,   1. ,   3. ,   5. ],
       [ 48.2,  23. ,   1. ,  32. ]])


来源:https://stackoverflow.com/questions/12253447/converting-a-list-of-ints-tuples-into-an-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!