计算列python中的顺序匹配值

时间:2017-11-10 09:16:44

标签: python count series sequential

我在数据框中有一个列:

x

0
0
0
1
1
1
1
0
0
1
1
1
0
0
0
0
1
1
1
1
1
1
1
1
0
0
0

我想要做的是创建一个新的列,它总结了彼此跟随的1组,只有当有超过3个相邻的1时才这样。所以我想要的输出是

x y
0 0
0 0
0 0
1 4
1 4
1 4
1 4
0 0
0 0
1 0
1 0
1 0
0 0
0 0
0 0
0 0
1 8 
1 8
1 8
1 8
1 8
1 8
1 8
1 8
0 0
0 0
0 0

所以在第一组1中,有四个,所以我在y列显示了4个。 在第二组1中,有三个,但我没有在y列显示计数。 在第三组1中,有8个,所以我应该在y列中计算8个。

非常感谢!

1 个答案:

答案 0 :(得分:0)

使用:

let ballToDisappear = sceneView?.scene.rootNode.childNodes(passingTest: { (node, stop) -> Bool in
    if (node.position.x < (maxVector?.x)! && node.position.x > (minVector?.x)!){
        if (node.position.y < (maxVector?.y)! && node.position.y > (minVector?.y)!){
            if (node.position.z < (maxVector?.z)! && node.position.z > (minVector?.z)!){
                return false // or false here and true below??
            }
        }
    }
                return true // or true here, see above, depends on your logic
}
)

另一个更快的解决方案:

#create Series for distinguish groups
a = df['x'].ne(df['x'].shift()).cumsum()
#remove 0 rows
df1 = df[df['x'] != 0]

#get counts, add 0 for zero rows and last replace values < 4
df['y'] = (df1.groupby(a)['x']
              .transform('size')
              .reindex(df.index, fill_value=0)
              .mask(lambda x: x < 4, 0))
#create groups
a = df['x'].ne(df['x'].shift()).cumsum()
#remove rows of groups where 0 and count output
b = a[df['x'] != 0].value_counts()
#get only values by condition
d = b[b >= 4]
#map to original, replace NaNs to 0 and last cast to int
df['y'] = a.map(d).fillna(0).astype(int)