【问题标题】:Why is my array coming out as shape: (6, 1, 2) when it is made of two (6, ) arrays?为什么我的数组由两个 (6, ) 数组组成时以 shape: (6, 1, 2) 的形式出现?
【发布时间】:2019-09-29 15:28:01
【问题描述】:

我正在尝试从 excel 导入数据并创建一个包含 6 行和 2 列的数组 pos。后来,当我去索引数组pos[0][1]时,我得到一个错误:IndexError: index 1 is out of bounds for axis 0 with size 1.

我查看了数组的形状,它返回 (6, 1, 2)。我期待得到(6, 2)。组成pos 的数组的各个形状是(6, )(6, ),我不太明白,为什么不(6, 1)?不太明白这两者的区别。

irmadata   = pd.read_excel("DangerZone.xlsx")
irma_lats  = irmadata["Average Latitude"].tolist()
irma_longs = irmadata["Average Longitude"].tolist()

shipdata   = pd.read_excel("ShipPositions.xlsx")
ship_lats  = shipdata["Latitude"].to_numpy()  ## these are the (6, ) arrays
ship_longs = shipdata["Longitude"].to_numpy()
pos = np.array([[ship_lats], [ship_longs]], dtype = "d").T

extent = [-10, -90, 0, 50]
ax = plot.axes(projection = crs.PlateCarree())
ax.stock_img()
ax.add_feature(cf.COASTLINE)
ax.coastlines(resolution = "50m")
ax.set_title("Base Map")
ax.set_extent(extent)

ax.plot(irma_longs, irma_lats)
for i in range(len(ship_lats)):
    lat = pos[i][0]
    lon = pos[i][1]   ## This is where my error occurs
    ax.plot(lon, lat, 'o', label = "Ship " + str(i+1))

plot.show()

显然,我可以索引pos[0][0][1] 但是,我想知道为什么我会遇到这个问题。我来自 MATLAB,所以我想我的很多问题都源于 numpy 和 MATLAB 工作方式的差异,因此任何提示也将不胜感激!

【问题讨论】:

  • 我相信问题出在ship_latsship_longs。请在问题或cmets中发布这两个的形状
  • 他们都是(6, )

标签: python arrays numpy multidimensional-array


【解决方案1】:

我解决了,我没有意识到我可以使用单个方括号来组合我的两个列数组。因此,将 pos = np.array([ship_lats], [ship_longs]], dtype = "d").T 更改为 pos = np.array([ship_lats, ship_longs], dtype = "d").T 有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2015-09-30
    • 2017-09-28
    • 2019-05-10
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多