根据行数不同的数据框创建3D数组

问题描述

我有一个这样的数据框:

enter image description here

仅使用时间列,经度列和纬度列,我想要创建一个形状为(2,16,2)的3D数组,其中第一个维度是时间(在这种情况下,有2次:2或3),第二个是代表每对lat-lon坐标的行总数,最后一个维度是lat-lon对

3d数组应如下所示:

    array([[[ 85.573875,-50.856796],[ 22.516417,-64.196556],[  4.072308,-48.226948],[ 24.439985,-47.150661],[129.924103,-50.699009],[296.879486,-20.473812],[       nan,nan],nan]],[[282.733734,-58.982613],[346.649414,-49.212891],[105.564247,-59.02515 ],[ 77.098854,-61.031345],[ 93.66552,-52.018295],[ 26.899933,-65.549835],[  8.558081,-48.222881],[ 28.211027,-50.188721],[137.030777,-51.931877],[295.907715,-20.918041],nan]]])

您可以从数据框中注意到,每个时间值(2和3)都有不同数量的数据/行。因此想法是,在第一次将时间从2更改为3之前,剩余的空值必须用NaN填充,然后移至第二次(时间= 3)。 NaN值的目的是保持阵列的形状(2,2)。

我不知道自己是否清楚。有谁能够帮助我? 谢谢。


编辑: 这是我到目前为止所做的:

假设df是我上面显示的数据框的名称

array1 = np.zeros((1,2)) #creates an empty array
for i in range(0,16):
    if (df.iloc[i,1]==2): #selects only the data with time=2
        array1[:,i,:] = [df.iloc[i,2],df.iloc[i,3]]
    else:
        array1[:,:] = [np.nan,np.nan] #fills the rest with NaN values

array2 = np.zeros((1,2))
for i in range(0,16): 
    if (df.iloc[i,1]==3): #selects only the data with time=3
        array2[:,3]]
    else:
        array2[:,np.nan] #fills the rest with NaN values

array2 = np.roll(array2,10,axis=1) #adjusts the position of the nan values

merged_arrays = np.vstack((array1,array2)) #the required final array,with shape (2,2)

我希望您能帮助我开发一种更直接,更清晰的方法,以便从数据框中创建此3D阵列。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)