[英]How do I count how often a column value changes in a pandas dataframe?
I have a pandas data frame that looks like:我有一个 pandas 数据框,如下所示:
Index Activity
0 0
1 0
2 1
3 1
4 1
5 0
...
1167 1
1168 0
1169 0
I want to count how many times it changes from 0 to 1 and when it changes from 1 to 0, but I do not want to count how many 1's or 0's there are.我想计算它从 0 变为 1 的次数以及从 1 变为 0 的时间,但我不想计算有多少个 1 或 0。 For example, if I only wanted to count index 0 to 5, the count for 0 to 1 would be one.
例如,如果我只想计算索引 0 到 5,那么 0 到 1 的计数将是 1。
How would I go about this?我将如何 go 关于这个? I have tried using some_value
我试过使用 some_value
This is a simple approach that can also tell you the index value when the change happens.这是一种简单的方法,还可以在更改发生时告诉您索引值。 Just add the index to a list.
只需将索引添加到列表中。
c_1to0 = 0
c_0to1 = 0
for i in range(0, df.shape[0]-1):
if df.iloc[i]['Activity'] == 0 and df.iloc[i+1]['Activity'] == 1:
c_0to1 +=1
elif df.iloc[i]['Activity'] == 1 and df.iloc[i+1]['Activity'] == 0:
c_1to0 +=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.