在numpy数组中逐行查找5个连续数字,忽略重复项 [英] Find 5 consecutive numbers in numpy array by row, ignore duplicates

查看:364
本文介绍了在numpy数组中逐行查找5个连续数字,忽略重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下阵列(3张7张卡片).它们按行排序,我想看看是否有5个连续的数字.下面的代码有效,但有一个错误:当有重复项(如第1行)时,结果不正确:

I have the following array (3 decks of 7 cards). They are sorted by row and I want to see if there are 5 consecutive numbers. The below code works but has a mistake: when there is a duplicate (like in row 1) the result is incorrect:

cards=
[[ 12.   6.   6.   5.   4.   2.   1.]
 [ 12.   9.   6.   6.   1.   1.   1.]
 [  6.   6.   1.   1.   0.   0.   0.]]

cardAmount=cards[0,:].size
has4=cards[:,np.arange(0,cardAmount-4)]-cards[:,np.arange(cardAmount-3,cardAmount)]
isStraight=np.any(has4 == 4, axis=1)

has4(显示相隔5个位置的任何纸牌之间是否存在4的差异)

has4 (shows if there is a difference of 4 between any of the cards 5 positions apart)

[[  8.   4.   5.]
 [ 11.   8.   5.]
 [  6.   6.   1.]]

isStraight检查是否有任何行包含4,这表示有一条直线.第一行的结果不正确,因为不会忽略重复项.

isStraight checks if any of the rows contains a 4, which means there is a straight. Result is incorrect for the first row because the duplicates are not ignored.

[ True False False]

困难之处在于numpy中无法按行逐个执行return_counts = True的np.unique,因为结果的长度是不同的.

The difficulty is that there is no way in numpy to do a np.unique with return_counts=True on a by row basis, as the results would have different lengths.

任何建议都值得赞赏.它只能是numpy(如果速度不受影响,则可以是熊猫).

Any suggestions are appreciated. It has to be numpy only (or pandas if the speed is not compromised).

推荐答案

我认为这是解决方案.有没有办法使它更简单?

I think this is the solution. Is there a way to make it even simpler?

iterations=3
cardAmount=cards[0,:].size
counts=(cards[:,:,None] == np.arange(12,0,-1)).sum(1) # occurences of each cards
present=counts
present[present>1]=1
s1=np.sum(present[:,0:5], axis=1)
s2=np.sum(present[:,1:6], axis=1)
s3=np.sum(present[:,2:7], axis=1)
s=np.stack((s1,s2,s3)).T
s[s < 5] = -1
s[s == 6] = 5
s[s ==7] = 5
s_index=np.argmax(s,axis=1)
straight=s[np.arange(iterations),s_index]>=0

这篇关于在numpy数组中逐行查找5个连续数字,忽略重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆