简体   繁体   中英

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,).

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.

Try:

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

print(arr)

Prints:

[0. 0. 4. 1. 0. 9.]

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