You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按Day、Element分组拼接满足Failure条件的Variable列字符串方法

实现代码

直接用pandas的筛选+分组聚合逻辑即可实现,代码如下:

import pandas as pd

# 示例数据构造,实际使用时替换为你自己的数据源读取逻辑即可
data = [
    ["2021-03-01 08:00:00", "2021-03-01", "A", "Current", 1],
    ["2021-03-01 08:00:00", "2021-03-01", "A", "Voltage", 1],
    ["2021-03-01 08:10:00", "2021-03-01", "A", "Current", 0],
    ["2021-03-01 08:10:00", "2021-03-01", "A", "Voltage", 0],
    ["2021-03-01 08:20:00", "2021-03-01", "A", "Current", 1],
    ["2021-03-01 08:20:00", "2021-03-01", "A", "Voltage", 1],
    ["2021-03-02 08:00:00", "2021-03-02", "B", "Current", 1],
    ["2021-03-02 08:00:00", "2021-03-02", "B", "Voltage", 0],
    ["2021-03-02 08:10:00", "2021-03-02", "B", "Current", 1],
    ["2021-03-02 08:10:00", "2021-03-02", "B", "Voltage", 0],
    ["2021-03-02 08:20:00", "2021-03-02", "B", "Current", 1],
    ["2021-03-02 08:20:00", "2021-03-02", "B", "Voltage", 0],
]
df = pd.DataFrame(data, columns=["Date", "Day", "Element", "Variable", "Failure"])

# 核心处理逻辑
result = (
    # 先筛选出所有Failure为1的记录
    df[df["Failure"] == 1]
    # 按Day、Element分组
    .groupby(["Day", "Element"], as_index=False)
    # Variable列去重后用逗号拼接
    .agg(Combination=("Variable", lambda x: ",".join(x.unique())))
)

print(result)

如果某个分组完全没有Failure==1的记录,会在第一步筛选时被全部过滤,最终结果不会展示该分组,刚好符合需求要求。

内容的提问来源于stack exchange,提问作者MustardRecord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:57:01