更新pandas datafram(条件复杂的元素的部分和)的最快方法

2024-05-13 21:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试更新一个有300万行的pandas数据帧。在下面,我把我的问题简化为一个更简单的问题。简言之,它确实在累积意义上增加了价值。在

但是,这个功能对我来说太长时间了,就像在一个真正的问题上超过10个小时。还有加速的余地吗?我应该最后才更新吗?在

我们可以用比iterrows()更快的方式更新pandas数据帧吗?在

我们可以根据索引选择多行然后更新吗?在

def set_r(group, i, colname, add):
    if colname in group:
        prev = group.iloc[i][colname]
        if  math.isnan(prev):
            group.set_value(i, colname, add)
        else:
            group.set_value(i, colname, prev+add)
    else:
        group.set_value(i, colname, add)

def set_bl_info(group, i, r, bl_value, timeframe, clorca, bl_criteria):

    group.set_value(i, timeframe + '_' + bl_criteria, True)
    colname = timeframe + '_' + clorca + '_' + 'bb_count_'+ bl_criteria
    set_r(group, i, colname, 1)

def bl_assign(days, bl_key, bl_value, group, bl_p05, bl_p01):
    print bl_key
    sub_group = group[(group.pledged_date >= bl_value[0]) & (group.pledged_date <= bl_value[1])]
    coexisting_icl = sub_group[(sub_group.project_category == bl_value[2]) & (sub_group.cluster == bl_value[3])]

    for i, r in coexisting_icl.iterrows():
        set_bl_info(group, i, r, bl_value, 'coexisting', 'icl','p1')


# main function
bl_assign(days, bl_key, bl_value, group, bl_p05, bl_p01)

为了简单起见,我的问题如下:

^{pr2}$

如果C为真且列元素之和为真,则更新B列

    A   B    C     
0   0   0   False
1   7   20   True
2   8   20   True
3   5   20   True

然后,如果D也是真的,则用E的和累计更新B

    A   B    C      D    E 
0   0   0   False False  1
1   7   20   True False  1
2   8   20   True True   1
3   5   20   True True   1

    A   B    C      D    E 
0   0   0   False False  1
1   7   20   True False  1
2   8   22   True True   1
3   5   22   True True   1

Tags: keyaddfalsetruevaluedefgroupset
1条回答
网友
1楼 · 发布于 2024-05-13 21:18:17

Update B column if C is true with sum of A column's elements

import numpy as np

df['B'] = np.where(df.C, df.A.sum(), 0)

After then, if D is also tru then update B with the sum of E (using the comment to the question above)

^{pr2}$

所以,最后你有

>>> df
   A      C   B  E      D
0  0  False   0  1  False
1  7   True  20  1  False
2  8   True  22  1   True
3  5   True  22  1   True

相关问题 更多 >