使用布尔函数在布尔值上分割熊猫数据框

时间:2019-03-08 16:37:14

标签: python pandas

我有一个功能

def return_true_false(a,b,c):
    '''
    returns true if stuff, else returns false
    '''

然后我将此功能两次应用于数据框,以将结果拆分为数据框

df_True =  df[df.apply(lambda x: return_true_false(x[a],x[b],x[c]),axis=1)]
df_false =  df[df.apply(lambda x: not return_true_false(x[a],x[b],x[c]),axis=1)]

但是,此操作每行两次进行计算。 我的问题是,有没有办法在函数上拆分此数据集,并且只浏览一次数据集?

1 个答案:

答案 0 :(得分:1)

IIUC,将结果赋给一次(例如,将其分配给 dt[0].Rows.Cast<DataRow>() .Select(r => new { pID = (long)r["ProcessID"], action = (string)r["ActionCode"] }) .Where(x => x.action == "A" || x.action == "E") .GroupBy(x => x.pID, x => x.action) .Where(g => new []{"A","E"}.Intersect(g).Count() == 2) .Select(g => g.Key); ),然后使用布尔索引:

mask