[英]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:我有一个如下所示的 pandas DataFrame:
x ![]() |
y![]() |
|
---|---|---|
0 ![]() |
2 ![]() |
4 ![]() |
1 ![]() |
3 ![]() |
1 ![]() |
2 ![]() |
5 ![]() |
9 ![]() |
All the x-values are unique.所有 x 值都是唯一的。 The x-values also tell the index of the corresponding number y in a numpy array.
x 值还告诉 numpy 数组中相应数字 y 的索引。
I have an np.zeros array that has a shape of (6,).我有一个形状为 (6,) 的 np.zeros 数组。
How can I efficiently modify the np.zeros array such that it will turn into np.array([0, 0, 4, 1, 0, 9)?如何有效地修改 np.zeros 数组,使其变为 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.
请注意索引 2 处的值为 4,因为根据 DataFrame,当 x = 2 时,y = 4。
Try:尝试:
arr = np.zeros(6)
arr[df["x"]] = df["y"]
print(arr)
Prints:印刷:
[0. 0. 4. 1. 0. 9.]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.