简体   繁体   中英

Error: can only convert an array of size 1 to a Python scalar

I have this code:

min_fit=np.min(fitness_viz) 
viz_min_fit=np.where(fitness_viz==min_fit)
index=np.asscalar(viz_min_fit[0])
tabu_list[0][1]=pair_ejec_cell_area[index][1]

The goal is to find the smallest value within an array (the fitness_viz array) and then the index of the smallest value (second line of the code). The viz_min_fit is an array with all the indexs that match the smallest value in the fitness_viz. Then, the goal is to use one of this indexs as an index in pair_ejec_cell_area. When I run this, I get an error saying "can only convert an array of size 1 to a Python scalar" that i don't understand.

Could someone help me? Thank you!

Your list of indexes is probably larger than one, so asscalar cannot choose which value to convert to a scalar.

>>> fitness_viz = [1, 1, 2, 3, 5]
>>> min_fit=np.min(fitness_viz) 
>>> viz_min_fit=np.where(fitness_viz==min_fit)
>>> len(viz_min_fit[0])
2

So one solution would be to fetch the first index:

>>> index=np.asscalar(viz_min_fit[0][:1])

Note that asscalar is deprecated since version 1.16, you can use numpy.ndarray.item() instead.

The full solution would be:

>>> fitness_viz = [1, 1, 2, 3, 5]
>>> min_fit=np.min(fitness_viz) 
>>> viz_min_fit=np.where(fitness_viz==min_fit)
>>> index=np.ndarray.item(viz_min_fit[0][:1]))
>>> tabu_list[0][1]=pair_ejec_cell_area[index][1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM