加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在具有不同多重性但相同维度的数组上同时使用numpy re

发布时间:2020-12-20 13:53:08 所属栏目:Python 来源:网络整理
导读:我有两个相同长度的trival数组,tmp_reds和tmp_blues: npts = 4tmp_reds = np.array(['red','red','red'])tmp_blues = np.array(['blue','blue','blue']) 我使用np.repeat创建多重性: red_occupations = [1,1,2]blue_occupations = [0,2,1]x = np.repeat(tm
我有两个相同长度的trival数组,tmp_reds和tmp_blues:

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

我使用np.repeat创建多重性:

red_occupations = [1,1,2]
blue_occupations = [0,2,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'])

因此,desired_array以下列方式定义:

(1)应用red_occupations的第一个元素的多重性

(2)应用blue_occupations的第一个元素的多重性

(3)应用red_occupations的第二个元素的多重性

(4)应用blue_occupations的第二个元素的多重性

(2 * npts-1)应用red_occupations的npts元素的多重性

(2 * npts)应用blue_occupations的npts元素的多重性

所以这似乎是np.repeat正常使用的直接概括.通常,np.repeat完全如上所述,但只有一个数组.有没有人知道一些聪明的方法来使用多维数组,然后使用np.repeat可以实现扁平化或其他类似技巧?

我总是可以创建desired_array而不使用numpy,使用简单的zipped for循环和连续列表追加.但是,实际问题有npts~1e7,速度很关键.

解决方法

对于一般情况 –

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

# Multiplicity arrays
color1_occupations = [1,2]
color2_occupations = [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','green','blue'],dtype='|S5')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读