数据框布尔过滤

时间:2020-01-28 09:48:04

标签: python pandas dataframe

rm_id  a         b       c      d   r_id
12  TRUE    TRUE    TRUE    0.2     1
13  TRUE    TRUE    TRUE    0.32    1
14  TRUE    TRUE    TRUE    0.02    1
15  TRUE    TRUE    FALSE   1.2     1
16  TRUE    TRUE    TRUE    0.05    1
17  FALSE   TRUE    FALSE   0.06    2
18  FALSE   TRUE    TRUE    0.8     1
19  TRUE    TRUE    FALSE   0.32    2
20  FALSE   TRUE    TRUE    0.54    1
13  TRUE    TRUE    FALSE   0.12    2
14  FALSE   TRUE    TRUE    0.012   2
16  FALSE   FALSE   FALSE   0.5     2
12  TRUE    FALSE   FALSE   0.9     2
11  FALSE   TRUE    TRUE    0.37    1

大家好: 我有上面的表格,当我通过r_id(即每一列的总和)过滤值时,我想获得如下所示的值。你能帮我吗?

rm_id a       b       c      d    r_id
12  TRUE    TRUE    TRUE    0.2     1
13  TRUE    TRUE    TRUE    0.32    1
14  TRUE    TRUE    TRUE    0.02    1
15  TRUE    TRUE    FALSE   1.2     1
16  TRUE    TRUE    TRUE    0.05    1
18  FALSE   TRUE    TRUE    0.8     1
20  FALSE   TRUE    TRUE    0.54    1
11  FALSE   TRUE    TRUE    0.37    1

    FALSE   TRUE    FALSE   3.5 

1 个答案:

答案 0 :(得分:0)

在字典中将GroupBy.aggGroupBy.allsum函数一起使用:

如果数据包含TRUEFALSE字符串,请使用:

print (df[['a','b','c']].dtypes)
a    object
b    object
c    object
dtype: object

#check real data
print (df[['a','b','c']].stack().unique())
['TRUE' 'FALSE']

#replace to boolean
df[['a','b','c']] = df[['a','b','c']].replace({'TRUE':True, 'FALSE':False})

print (df[['a','b','c']].dtypes)
a    bool
b    bool
c    bool
dtype: object

df1 = df.groupby('r_id', as_index=False).agg({'a':'all', 'b':'all','c':'all', 'd':'sum'})
print (df1)
   r_id      a      b      c      d
0     1  False   True  False  3.500
1     2  False  False  False  1.912