按列(“租户”)分组并获取(“值”)列中最大连续 1

发布于 2025-01-14 14:31:28 字数 437 浏览 1 评论 0原文

我有一个如下所示的 df:

租户价值
x1
x1
x0
x1
y1
y0

结果: 租户 X 应为 2,租户 y 应为 1

我正在尝试获取每组的最大连续值 1。如果值 1 之间有任何 0,则计数重新开始。 我是 python 新手,不知道从哪里开始。谢谢

I have a df shown below:

TenantValue
x1
x1
x0
x1
y1
y0

Results:
Tenant X should be 2 and tenant y should be 1

I am trying to get the max consecutive value 1s per group. If there are any 0 in between the value 1 the count starts over.
I am new to python and not sure where to start. Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海夕 2025-01-21 14:31:28

您可以尝试:

def max_ones(col):
    return col.groupby(col.diff().ne(0).cumsum()).sum().max()

result = df.groupby("Tenant").Value.agg(max_ones)

如果 Value 列可以有 01 以外的其他值,您应该使用:

result = df.assign(Value=df.Value.eq(1)).groupby("Tenant").Value.agg(max_ones)

You could try:

def max_ones(col):
    return col.groupby(col.diff().ne(0).cumsum()).sum().max()

result = df.groupby("Tenant").Value.agg(max_ones)

If the Value column can have other values than 0 or 1 you should rather use:

result = df.assign(Value=df.Value.eq(1)).groupby("Tenant").Value.agg(max_ones)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文