Pandas:在列中计算一些值

2024-04-20 12:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的数据帧:

ID   value
111   1
111   0
111   1
111   0
111   0
111   0
111   1
222   1
222   0
222   0
222   1

对于每个ID,我需要一行中出现0的最大次数。 在这种情况下,由于0在ID 111一行中出现三次,对于{},一行中出现两次,因此所需的输出应该是:

^{pr2}$

value_counts没有执行我想要的操作,因为它计算列中的所有值。在

我怎么能做到呢?在


Tags: 数据idvalue情况次数countspr2
3条回答
aggregations = {
    'value': {
        'total': 'sum'
    }
}
dftwo = df.groupby('ID').agg(aggregations)

dataframe

你可以利用

iszero = (df['value']==0)
df['group'] = (iszero.diff()==1).cumsum()

要为每行指定一个组号:

^{pr2}$

现在可以按IDgroup编号分组,以获得所需的值计数:

^{3}$

收益率

ID
111    3
222    2
Name: group, dtype: int64

这应该是有效的:

import numpy as np

# load data etc
...

def get_count_max_0(df):
    """
    Computes the max length of a sequence of zeroes
    broken by ones.
    """
    values = np.array(df['value'].tolist())
    # compute change points where 0 -> 1
    cps_1 = np.where(
        (values[1:] != values[:-1]) &
        (values[1:] == 1)
    )[0]
    # compute change points where 1 -> 0
    cps_0 = np.where(
        (values[1:] != values[:-1]) &
        (values[1:] == 0)
    )[0]

    # find lengths of zero chains
    deltas = cps_1 - cps_0
    # get index of max length
    idx = np.where(deltas == deltas.max())[0][0]
    # return max length
    return deltas[idx]

# group by ID, apply get_count_max_0 to each group and 
# convert resulting series back to data frame to match your expected output.
max_counts = df.groupby("ID").apply(get_count_max_0).to_frame("count_max_0")

print(max_counts)

输出为:

^{pr2}$

相关问题 更多 >