我们有一个形式为 (year, value) 的元组列表:

splist

[(2002, 10.502535211267606),
 (2003, 10.214794520547946),
 (2004, 9.8115789473684227),
  ..
 (2015, 9.0936585365853659),
 (2016, 9.2442725379351387)]

目的是将元组列表转换为二维 numpy 数组。然而,使用 np.asarray 的已发布答案保留了一个维度:
dt = np.dtype('int,float')
spp = np.asarray(splist,dt)

spp
   array([(2002, 10.502535211267606), (2003, 10.214794520547946),
   (2004, 9.811578947368423), (2005, 9.684155844155844),
   ..
   (2014, 9.438987341772153), (2015, 9.093658536585366),
   (2016, 9.244272537935139)],
  dtype=[('f0', '<i8'), ('f1', '<f8')])

查看输出的维度时,这一点变得清晰:
In [155]: spp.shape
Out[155]: (15,)

我们想要的:
   array([[(2002, 10.502535211267606)],
        [(2003, 10.214794520547946)],
   ..
   [(2014, 9.438987341772153)],
   [(2015, 9.093658536585366)],
   [(2016, 9.244272537935139)]])

那么将元组列表转换为 两个 维数组的魔法是什么?

最佳答案

如果我正确理解您想要的输出,您可以使用 numpy.reshape

>>> spp = np.asarray(splist, dt)
>>> spp
array([(2002, 10.502535211267606),
       (2003, 10.214794520547946),
       (2004, 9.811578947368423),
       (2015, 9.093658536585366),
       (2016, 9.244272537935139)],
      dtype=[('f0', '<i4'), ('f1', '<f8')])

>>> np.reshape(spp, (spp.size, 1))
array([[(2002, 10.502535211267606)],
       [(2003, 10.214794520547946)],
       [(2004, 9.811578947368423)],
       [(2015, 9.093658536585366)],
       [(2016, 9.244272537935139)]],
      dtype=[('f0', '<i4'), ('f1', '<f8')])

关于python - 将元组列表转换为 numpy 数组会导致一维,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40596672/

10-12 15:55