繁体   English   中英

从pandas数据框创建np.array,该数据框有一列保存数组索引的值,另一列保存每个索引的值?

[英]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?

我有一个如下所示的 pandas DataFrame:

X 是的
0 2 4
1 3 1
2 5 9

所有 x 值都是唯一的。 x 值还告诉 numpy 数组中相应数字 y 的索引。

我有一个形状为 (6,) 的 np.zeros 数组。

如何有效地修改 np.zeros 数组,使其变为 np.array([0, 0, 4, 1, 0, 9)? 请注意索引 2 处的值为 4,因为根据 DataFrame,当 x = 2 时,y = 4。

尝试:

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

print(arr)

印刷:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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