首页 > 解决方案 > 为数据框编写循环时出现问题

问题描述

我有一个包含两列“ENTRYP”和“Status”的数据框。如果 ENTRYP 的值小于或等于 0.02,则应将“状态”更改为“ENT_EXT”。每次越过该范围时,它都应将计数添加到状态。例如:movement1、ent_ext1、movement2、ent_Ext2。我已经写了下面的代码,但它抛出了下面的错误

Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

h_count = 0
current = "ENT_EXT"
current == "MOVING"

status_halt = []

for idx in df2.index:
    if (df2["ENTRYP"][idx] <= 0.02):
        if current == "MOVING":
            h_count += 1
        status_halt.append(f"ENT_EXT{h_count}")
        current = "ENT_EXT"
    elif (df2["ENTRYP"][idx] > 0.02):
        if current == "ENT_EXT":
            m_count += 1
        status_halt.append(f"MOVING_{m_count}")
        current = "MOVING"

df2["Status"] = status_halt

我添加了数据框的片段和所需的输出。

请让我知道如何继续https://i.stack.imgur.com/K0Qsj.png

标签: pythondataframeif-statement

解决方案


我想我得到了你需要的东西,虽然获得它的功能有点复杂。对于小于等于 0.02 的情况,我在注释中解释了我的代码,但对于大于 0.02 的情况,逻辑完全相同。

import pandas as pd
a=[0.04, 0.04, 0.02, 0.02, 0.03, 0.03, 0.02, 0.01]
adf=pd.DataFrame(a, columns=["ENTRYP"])

def afunct(ent):
    stats=["MOVEMENT_","ENT_EXT"]
    c_status=[]
    m_counter=0
    e_counter=0
    for i in ent:
        if(i <= 0.02): # cases when the value is less equal that 0.02 (it's ENT_EXT")
            if(len(c_status)==0): # if the list is empty we initialize the counters for "M" and "E" and put the first STATUS
                m_counter=0
                e_counter=1
                c_status.append("{}{}".format(stats[1],e_counter ))
            elif(c_status[-1][0]=="E"):  ## if the last status is a "E" we just add another "ENT_EXT"
                c_status.append("{}{}".format(stats[1],e_counter ))
            elif(c_status[-1][0]=="M"): # if the last status is a "M" we add to the e_counter and assign STATUS
                e_counter+=1
                c_status.append("{}{}".format(stats[1],e_counter ))
        elif(i>0.02):
            if(len(c_status)==0):
                m_counter=1
                e_counter=0
                c_status.append("{}{}".format(stats[0],m_counter ))
            elif(c_status[-1][0]=="M"):
                c_status.append("{}{}".format(stats[0],m_counter ))
            elif(c_status[-1][0]=="E"):
                m_counter+=1
                c_status.append("{}{}".format(stats[0],m_counter ))
    return(c_status)

adf["STATUS"]=afunct(adf["ENTRYP"])

结果:

    ENTRYP  STATUS
0   0.04    MOVEMENT_1
1   0.04    MOVEMENT_1
2   0.02    ENT_EXT1
3   0.02    ENT_EXT1
4   0.03    MOVEMENT_2
5   0.03    MOVEMENT_2
6   0.02    ENT_EXT2
7   0.01    ENT_EXT2

推荐阅读