对具有不同多重性但维数相同的数组同时使用numpy repeat

2024-06-01 02:00:33 发布

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

我有两个相同长度的平凡数组,tmp\u redstmp\u blues

npts = 4
tmp_reds = np.array(['red', 'red', 'red', 'red'])
tmp_blues = np.array(['blue', 'blue', 'blue', 'blue'])

我正在使用np.重复要创建多重性:

red_occupations = [1, 0, 1, 2]
blue_occupations = [0, 2, 0, 1]

x = np.repeat(tmp_reds, red_occupations)
y = np.repeat(tmp_blues, blue_occupations)

print(x)
['red' 'red' 'red' 'red']

print(y)
['blue' 'blue' 'blue']

我想要的是下面的x和y的组合:

desired_array = np.array(['red', 'blue', 'blue', 'red', 'red', 'red', 'blue'])

因此,所需的_数组按以下方式定义:

(1)应用红色职业第一要素的多重性

(2)应用蓝色职业第一要素的多重性

(3)应用红色职业第二要素的多重性

(4)应用蓝色职业第二要素的多重性

。。。你知道吗

(2*npts-1)应用了红色职业npts元素的多重性

(2*npts)应用蓝色职业的npts元素的多重性

所以这看起来像是对np.重复. 正常情况下,np.重复完全执行上述操作,但使用单个数组。有人知道一些聪明的方法来使用多维数组,然后展平,或其他类似的技巧,可以实现这一点吗重复一遍?你知道吗

我总是可以创建所需的\u数组,而不使用numpy,使用一个简单的zipped for循环和连续的列表附件。然而,实际问题有npts~1e7,速度是关键。你知道吗


Tags: npbluered数组arraytmp蓝色要素
1条回答
网友
1楼 · 发布于 2024-06-01 02:00:33

对于一般情况-

# Two 1D color arrays
tmp1 = np.array(['red', 'red', 'red', 'green'])
tmp2 = np.array(['white', 'black', 'blue', 'blue'])

# Multiplicity arrays
color1_occupations = [1, 0, 1, 2]
color2_occupations = [0, 2, 0, 1]

# Stack those two color arrays and two multiplicity arrays separately
tmp12 = np.column_stack((tmp1,tmp2))
color_occupations = np.column_stack((color1_occupations,color2_occupations))

# Use np.repeat to get stacked multiplicities for stacked color arrays
out = np.repeat(tmp12,color_occupations.ravel())

给我们-

In [180]: out
Out[180]: 
array(['red', 'black', 'black', 'red', 'green', 'green', 'blue'], 
      dtype='|S5')

相关问题 更多 >