0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

連続するデータの変化の回数を数える

Posted at

#連続するデータの変化の回数を数える。
以下のテストデータでarea毎にvalの値が変化する回数を数える
#テストデータ

import pandas as pd

dt={
    "area" :[1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2],
    "seq"  :[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8],
    "val"  :[1,2,2,1,3,3,3,1,1,1,2,2,2,1,1,2]
    }
df=pd.DataFrame(dt)

print(df.to_markdown()) 
area seq val
0 1 1 1
1 1 2 2
2 1 3 2
3 1 4 1
4 1 5 3
5 1 6 3
6 1 7 3
7 1 8 1
8 2 1 1
9 2 2 1
10 2 3 2
11 2 4 2
12 2 5 2
13 2 6 1
14 2 7 1
15 2 8 2

#期待する答え
area 1:5個
area 2:4個

#変化の回数のカウント

#変化点を求める
df.sort_values(["area" , "seq"] ,inplace=True)
df["cnt"]=df.groupby(["area"])["val"].diff().apply(lambda x:0 if x==0 else 1 )
print("変化点") 
print(df.to_markdown()) 

#変化の回数
df2=df.groupby(["area"]).cnt.sum()
print("変化の回数")
print(df2.to_markdown()) 

#変化点

area seq val cnt
0 1 1 1 1
1 1 2 2 1
2 1 3 2 0
3 1 4 1 1
4 1 5 3 1
5 1 6 3 0
6 1 7 3 0
7 1 8 1 1
8 2 1 1 1
9 2 2 1 0
10 2 3 2 1
11 2 4 2 0
12 2 5 2 0
13 2 6 1 1
14 2 7 1 0
15 2 8 2 1
#変化の回数
area cnt
-------: ------:
1 5
2 4
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?