gpt4 book ai didi

python - 在numpy数组中的其他值之间插入值

转载 作者:行者123 更新时间:2023-12-04 09:17:09 25 4
gpt4 key购买 nike

假设我从这个数组开始:

start_array = [[1.48, 1.79, 2.10, 2.80]
[63, 60, 57, 60]]
我想取第二个数组中的值:
second_array = np.array([2.3,3.42, 4.47])
并将它们插入第一行的值之间,在另一行中插入 1 来编码那里发生的事情。其余位置应填零。
结果:
result = np.array([[1.48, 1.79, 2.10, 2.3, 2.80, 3.42, 4.47],
[63., 60., 57., 0, 60., 0, 0],
[0, 0, 0, 1, 0, 1, 1]
])

最佳答案

这是一种基于 n​​umpy 的方法:

# flatten start, and searchsorted to see where to insert
start_array_view = start_array.ravel()
ixs = np.searchsorted(start_array_view, second_array) + np.arange(len(second_array))
# construct output array
x,y = start_array.shape
out = np.zeros((x,y+len(ixs)))
# insert values from second array
z_pad = [0]*(len(ixs)*out.shape[0]-len(second_array))
out[:,ixs] = np.r_[second_array,z_pad ].reshape(out.shape[0],-1)
# insert values from start array
ar = np.arange(out.shape[1])
ixs_start = ar[~np.isin(ar, ixs)]
out[:,ixs_start] = start_array
# add indicator row
z = np.zeros(out.shape[1])
z[ixs] = 1
out = np.vstack([out,z])
print(out)
array([[ 1.48, 1.79, 2.1 , 2.3 , 2.8 , 3.42, 4.47],
[63. , 60. , 57. , 0. , 60. , 0. , 0. ],
[ 0. , 0. , 0. , 1. , 0. , 1. , 1. ]])

关于python - 在numpy数组中的其他值之间插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com