use*_*836 5 python group-by count pandas
我想在这里做他们在答案中所做的事情:在 pandas 中以矢量化方式计算特定连续相等值的数量 ,但使用分组数据帧而不是系列。
所以给定一个有几列的数据框
A B C
------------
x x 0
x x 5
x x 2
x x 0
x x 0
x x 3
x x 0
y x 1
y x 10
y x 0
y x 5
y x 0
y x 0
Run Code Online (Sandbox Code Playgroud)
我想对 A 列和 B 列进行分组,然后计算 C 中连续零的数量。之后我想返回每个零长度出现次数的计数。所以我想要这样的输出:
A B num_consecutive_zeros count
---------------------------------------
x x 1 2
x x 2 1
y x 1 1
y x 2 1
Run Code Online (Sandbox Code Playgroud)
我不知道如何调整链接问题的答案来处理分组数据框。
这是代码,count_consecutive_zeros()使用 numpy 函数并pandas.value_counts()获取结果,并使用groupby().apply(count_consecutive_zeros)来调用count_consecutive_zeros()每个组。调用reset_index()更改MultiIndex列:
import pandas as pd
import numpy as np
from io import BytesIO
text = """A B C
x x 0
x x 5
x x 2
x x 0
x x 0
x x 3
x x 0
y x 1
y x 10
y x 0
y x 5
y x 0
y x 0"""
df = pd.read_csv(BytesIO(text.encode()), delim_whitespace=True)
def count_consecutive_zeros(s):
v = np.diff(np.r_[0, s.values==0, 0])
s = pd.value_counts(np.where(v == -1)[0] - np.where(v == 1)[0])
s.index.name = "num_consecutive_zeros"
s.name = "count"
return s
df.groupby(["A", "B"]).C.apply(count_consecutive_zeros).reset_index()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3322 次 |
| 最近记录: |