python - 如何计算 Pandas 状态变化的次数?

标签 python pandas dataframe

我有下面的数据框,其中有 0-1 列 .. 我想 计算每列 0->1,1->0 的数量。在下面的数据框中 'a' 列状态变化数为 6,'b' 状态变化数为 3 , 'c' state change number is 2 .. 其实我不知道怎么 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

实际上我对 pandas 没有概念.. 因为最近只用过 r. 但现在我必须使用 python pandas。所以有点困难 情况有人可以帮忙吗?提前致谢 !

最佳答案

使用rolling并比较每个值,然后通过 sum 计算所有 True 值:

df = df[['a','b','c']].rolling(2).apply(lambda x: x[0] != x[-1], raw=True).sum().astype(int)
a    6
b    3
c    2
dtype: int64

关于python - 如何计算 Pandas 状态变化的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53189792/

相关文章:

python - 验证正则表达式中的单点和空格

python - 使用 re 替换数组的一部分

python - 我将如何选择 pandas 中与字符串列表匹配的行,而不仅仅是一个特定的字符串?

python - 比较两列并用数字替换 NaN

Python 选择数据框中每组前 3 个值的数据

python - 在python中使用pandas时如何修复 "Attribute error"

python - 如何从这种字符串中删除不需要的字符?

Python Pandas 库按截断日期重新采样

python - django 上传文件,处理 pandas 并下载为 csv

python - Pandas 数据框 : how to select rows where one column-value is like 'values in a list'