Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create np.array from pandas dataframe which has a column holding values of the array's indices and another column holding the value at each index?

I have a pandas DataFrame that looks like the following:

x y
0 2 4
1 3 1
2 5 9

All the x-values are unique. The x-values also tell the index of the corresponding number y in a numpy array.

I have an np.zeros array that has a shape of (6,).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I efficiently modify the np.zeros array such that it will turn into
np.array([0, 0, 4, 1, 0, 9)?
Notice how at index 2, the value is 4 because when x = 2, y = 4 according to the DataFrame.

>Solution :

Try:

arr = np.zeros(6)
arr[df["x"]] = df["y"]

print(arr)

Prints:

[0. 0. 4. 1. 0. 9.]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading