【问题标题】:Pandas compare next row and merge based on conditions熊猫比较下一行并根据条件合并
【发布时间】:2020-11-11 22:26:35
【问题描述】:

【问题讨论】:

    标签: python merge conditional-statements row next


    【解决方案1】:

    样本 DF

           Start    Time   End      ID
      0    43500    60     43560    23
      1    43560    60     43620    23 
      2    43620    1020   44640    24 
      3    44640    260    44900    24
      4    44900    2100   47000    24
    

    代码:

    a = df["ID"].tolist()
    arr = [] 
    t = True
    for i in sorted(list(set(a))):
        j = 1
        k = 0
        temp = {}
        tempdf = df[df["ID"] == i]
        temp["Start"] = tempdf.iloc[k]["Start"]
        temp["Time"] = tempdf.iloc[k]["Time"]
        temp["End"] = tempdf.iloc[k]["End"]   
        temp["ID"] = tempdf.iloc[k]["ID"]
    
        while j < len(tempdf):
            if temp["End"] == tempdf.iloc[j]["Start"]:
                temp["End"] = tempdf.iloc[j]["End"]
                temp["Time"] += tempdf.iloc[j]["Time"] 
             j += 1  
            
        arr.append(temp)       
    
    df = pd.DataFrame(arr)
    

    输出DF:

            Start   Time    End     ID
       0    43500   120     43620   23   
       1    43620   3380    47000   24
    

    【讨论】:

    • 感谢您的帮助。但是,如果我有 4 行 end = start 且 ID 相同怎么办?我想要 4 行合并到 1
    • 嗯,乐于助人:)
    【解决方案2】:

    我不确定您的数据是如何准确格式化的,但您可以替换。 我建议你使用 numpy 并尝试一些类似的东西:

    i=0
    while i != len(data):
        if data[i][4] == data[i+1][2]:
            data[i][4] = data[i+1][2]
            data[i+1].pop
        else :
            i+=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多