how to count the number of state change in pandas?

3394 views pandas
3

i have below dataframe that have columns 0-1 .. and i wanna count the number of 0->1,1->0 every column. in below dataframe 'a' column state change number is 6, 'b' state change number is 3 , 'c' state change number is 2 .. actually i don't know how code in pandas.

number a b c
--------------
1      0 0 0
2      1 0 1
3      0 1 1
4      1 1 1
5      0 0 0
6      1 0 0
7      0 1 0
---------------

actually i don't have idea in pandas.. because recently used only r. but now i must use python pandas. so have little bit in difficult situation anybody can help ? thanks in advance !

answered question

3 Answers

7

Use:

df = df.iloc[:, 1:].rolling(2).apply(lambda x: x[0] != x[-1]).eq(1).sum()
print (df)
a    6
b    3
c    2
dtype: int64

posted this
9

You can try of taking difference with previous one and add absolute valeues

df.diff().abs().sum()

Out:

1    6.0
2    3.0
3    2.0
dtype: float64

posted this
1

Use:

def agg_columns(x):
    shifted = x.shift()
    return sum(x[1:] != shifted[1:])

df[['a','b','c']].apply(agg_columns)

a    6
b    3
c    2
dtype: int64

posted this

Have an answer?

JD

Please login first before posting an answer.