簡體   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