# how to count the number of state change in pandas?

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 !

jezrael
answered question

### 3 Answers

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
```

Naga Kiran
posted this

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
```

Franco Piccolo
posted this

## Have an answer?

JD