2017-01-27 2 views
3

パンダシリーズでは、TrueまたはFalseのスジを表示する方法を工夫しています。パンダで真実か偽のかすれシリーズ

データ:

p = pd.Series([True,False,True,True,True,True,False,False,True]) 

0  True 
1 False 
2  True 
3  True 
4  True 
5  True 
6 False 
7 False 
8  True 
dtype: bool 

私は、これは次のようである私の所望の出力を表示するために生成False値をカウントする方法がわからp.diff()を試みたが、ない:. pshiftpcumsumと等しくない場合

0  0 
1  0 
2  0 
3  1 
4  2 
5  3 
6  0 
7  1 
8  0 

答えて

3

あなたは比較によって作成されたconsecutivesグループのcumcountを使用することができます。

print (p.ne(p.shift())) 
0  True 
1  True 
2  True 
3 False 
4 False 
5 False 
6  True 
7 False 
8  True 
dtype: bool 

print (p.ne(p.shift()).cumsum()) 
0 1 
1 2 
2 3 
3 3 
4 3 
5 3 
6 4 
7 4 
8 5 
dtype: int32 

print (p.groupby(p.ne(p.shift()).cumsum()).cumcount()) 
0 0 
1 0 
2 0 
3 1 
4 2 
5 3 
6 0 
7 1 
8 0 
dtype: int64 

は別のソリューションをおMaxUありがとう:

print (p.groupby(p.diff().cumsum()).cumcount()) 
0 0 
1 0 
2 0 
3 1 
4 2 
5 3 
6 0 
7 1 
8 0 
dtype: int64 
+1

@MaxU - ありがとう;) – jezrael

+0

は良い:-)おかげと感謝を見える@MaxU – ade1e

0

もう1つの代替ソリューションは、累積合計をpSeriesを入力し、p0である最新の累積合計を減算します。その後、pを逆にして同じ操作を行います。一緒に最後の複数のSeries

c = p.cumsum() 
a = c.sub(c.mask(p).ffill(), fill_value=0).sub(1).abs() 
c = (~p).cumsum() 
d = c.sub(c.mask(~(p)).ffill(), fill_value=0).sub(1).abs() 

print (a) 
0 0.0 
1 1.0 
2 0.0 
3 1.0 
4 2.0 
5 3.0 
6 1.0 
7 1.0 
8 0.0 
dtype: float64 

print (d) 
0 1.0 
1 0.0 
2 1.0 
3 1.0 
4 1.0 
5 1.0 
6 0.0 
7 1.0 
8 1.0 
dtype: float64 
print (a.mul(d).astype(int)) 
0 0 
1 0 
2 0 
3 1 
4 2 
5 3 
6 0 
7 1 
8 0 
dtype: int32 
関連する問題