如何使pd.Dataframe列分配更快?

时间:2018-12-03 09:39:02

标签: python pandas performance assign

因此,我试图通过逻辑比较将列添加到现有数据框中:

def qualitycheck(data, qparams, qid):
    data = data.assign(parameter_set = qid)
    data = data.assign(volume_below_max = (data["volume"] < int(qparams["max_volume"])))
    data = data.assign(volume_trucks_below_max = (data["volume_trucks"]  < int(qparams["max_volume_trucks"])))
    data = data.assign(volume_cars_below_max = (data["volume_cars"] < int(qparams["max_volume_cars"])))
    data = data.assign(volume_diffcheck_ok = diffcheck(data["volume"]))
    data = data.assign(occupancy_below_max = data["occupancy"]  < int(qparams["max_occupancy"]))
    data = data.assign(occupancy_diffcheck_ok = diffcheck(data["occupancy"]))
    data = data.assign(speed_below_max = data["speed"] < int(qparams["max_speed"]))
    data = data.assign(speed_trucks_below_max= data["speed_trucks"]  < int(qparams["max_speed_trucks"]))
    data = data.assign(speed_cars_below_max = data["speed_cars"] < int(qparams["max_speed_cars"]))
    data = data.assign(speed_diffcheck_ok = diffcheck(data["speed"]))
    data = data.assign(volume_speed_plausible = q_v_plaus(data["volume"], data["speed"]))
    data = data.assign(net_time_gap_below_max = data["net_time_gap"] < 60)
    data = data.assign(speed_occupancy_plausible = v_occ_plaus(data["speed"], data["occupancy"], qparams))   
return data

这些.assigns中使用的三个函数也只是对所提供的两列的逻辑比较。 “ qparams”是一个DataFrame,其中包含一些常量。每次调用此qualitycheck()函数时,都会传入具有5行的数据帧,然后将其扩展为这14列并返回。使用%timeit,此功能的时间为11.9ms。问题是,我不得不称它为2500万次,这将导致大约83h。

那么有什么方法可以改善此功能的性能?

编辑:这是三个功能:

def diffcheck(column):
    if column.sum() == 0:
        return True
    val0 = column.iloc[0]
    check = val0 == column
    if check.sum() < len(check):
        return True
    else:
        return False

def q_v_plaus(qs,vs):
    plaus = []
    for i in range(0,5):
        q = qs.iloc[i]
        v = vs.iloc[i]
        if q == 0 and v > 0:
            plaus.append(False)
        elif q > 0 and v == 0:
            plaus.append(False)
        else:
            plaus.append(True)
    return plaus

1 个答案:

答案 0 :(得分:0)

主要问题是您针对5行大块调用此函数,更好的性能应该针对1k,10k行大块。

函数DataFrame.assign稍慢一些,但是主要问题应该在您的自定义函数diffcheckq_v_plausv_occ_plaus中-我想没有向量化(如果可能的话)不能不说就说)。

删除assign并与.values进行比较,将Series替换为1d numpy array

def qualitycheck(data, qparams, qid):
    data['parameter_set'] = qid
    data['volume_below_max'] = data["volume"].values < int(qparams["max_volume"])
    ...
    ...    

我尝试优化您的功能:

def diffcheck(column):
    if column.values.sum() == 0:
        return True
    val0 = column.iat[0]
    check = val0 == column
    return check.values.sum() < len(check)

该功能适用​​于所有行,不仅适用于前5行:

def q_v_plaus1(qs,vs):
    qs = qs.values
    vs= vs.values
    m1 = (qs== 0) & (vs > 0)
    m2 = (qs> 0) & (vs == 0)
    return ~(m1 | m2)

被重写为更快的替代方法:

def q_v_plaus1(qs,vs):
    qs = qs.values
    vs= vs.values
    m1 = (qs!= 0) | (vs <= 0)
    m2 = (qs<= 0) | (vs != 0)
    return m1 & m2