我有一个数据帧和一个与数据帧对应的索引表。要创建新的数据帧,是否有其他方法来重建新数据。索引表中的行索引实际上是行号,因此在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]])
假设您有一些值
vals
,和一些索引ind
:获取所需内容的最简单方法是使用多维索引:
如果您的问题似乎暗示您的值在
pd.DataFrame
中,那么您可以访问values
属性来处理底层的np.array
:相关问题 更多 >
编程相关推荐