简体   繁体   中英

How can i change a numpy.ndarray to point format with curly brackets - Python 3.7

I'm still new to Python, but developing a small Web App with Django, where I use Charts.js to generate a Scatterplot. The actual result I get is in the format of a numpy.ndarray .

Id like to convert it to the necessary "point format" like stated in the Charts.js documentation: https://www.chartjs.org/docs/latest/charts/scatter.html

Would be great if you have some simple ideas.

Current Datastructure:

result = 

    [[4.212000 8.954910]

 [4.467000 9.599410]

 [3.849000 9.235800]

 ...

[4.941000 7.130224]

[3.555000 4.513942]

[4.836000 4.868685]]

Desired Structure:

new_result = 

[{x: 4.212000, y: 8.954910},

{x: 4.467000, y: 9.599410},

{x: 3.849000, y: 9.235800},

...

{x: 4.941000, y: 7.130224},

{x: 3.555000, y: 4.513942},

{x: 4.836000, y: 4.868685}]

I know the question is probably pretty basic, but I got stuck for hours, looking for solutions.

您可以使用列表理解

new_result = [{'x': el[0], 'y': el[1]} for el in result]

try sth like:

def convert_array(arr):
    return [{'x':item[0],'y':item[1]} for item in arr]

use as:

converted_array = convert_array(numpy_array)

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