【问题标题】: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数据框创建np.array,该数据框有一列保存数组索引的值,另一列保存每个索引的值?
【发布时间】:2022-07-11 00:10:05
【问题描述】:

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

x y
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。

【问题讨论】:

    标签: python arrays pandas numpy


    【解决方案1】:

    试试:

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

    打印:

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

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2020-10-11
      • 2019-02-13
      • 2020-08-06
      • 2018-03-13
      • 1970-01-01
      • 2021-10-14
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多