给定索引矩阵和原始数据,如何快速重建新的数据帧

2024-09-19 20:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧和一个与数据帧对应的索引表。要创建新的数据帧,是否有其他方法来重建新数据。索引表中的行索引实际上是行号,因此在python意义上,实际的行索引=行号-1

    # simulate index table
    col_index=np.random.choice([0,1], 5, p=[0.4, 0.6])
    row_index=np.random.choice([3,1,2],5, p=[0.4, 0.5,0.1])
    ind=np.vstack((row_index,col_index))
    ind=ind.T

    array([[3, 0],
   [3, 1],
   [2, 1],
   [1, 1],
   [1, 0]])

    dt=np.random.random((5, 2)) #simulated data

    array([[ 0.3592,  0.4983],
       [ 0.0518,  0.2291],
       [ 0.4322,  0.5654],
       [ 0.8482,  0.1722],
       [ 0.1448,  0.5766]])

    # My code
    newDt=np.zeros([5,1])
    for j in range(5):
        row=ind[j,0]
        col=ind[j,1]
        newDt[j]=dt[row-1,col]

    #output
    array([[ 0.4322],
       [ 0.5654],
       [ 0.2291],
       [ 0.4983],
       [ 0.3592]])

Tags: 数据方法indexnpdtcolrandomarray
1条回答
网友
1楼 · 发布于 2024-09-19 20:51:24

假设您有一些值vals,和一些索引ind

>>> vals
array([[ 0.3592,  0.4983],
       [ 0.0518,  0.2291],
       [ 0.4322,  0.5654],
       [ 0.8482,  0.1722],
       [ 0.1448,  0.5766]])
>>> ind
array([[3, 0],
       [3, 1],
       [2, 1],
       [1, 1],
       [1, 0]])

获取所需内容的最简单方法是使用多维索引:

>>> vals[ind[:,0] - 1, ind[:,1]]
array([ 0.4322,  0.5654,  0.2291,  0.4983,  0.3592])

如果您的问题似乎暗示您的值在pd.DataFrame中,那么您可以访问values属性来处理底层的np.array

>>> df
        0       1
0  0.3592  0.4983
1  0.0518  0.2291
2  0.4322  0.5654
3  0.8482  0.1722
4  0.1448  0.5766
>>> df.values[ind[:,0] - 1, ind[:,1]]
array([ 0.4322,  0.5654,  0.2291,  0.4983,  0.3592])

相关问题 更多 >