Python 如何使用pandas聚合具有空值的布尔字段?

Python 如何使用pandas聚合具有空值的布尔字段?,python,pandas,aggregate,Python,Pandas,Aggregate,我第一次和熊猫一起工作,我在聚合方面遇到了一些问题。我有一个dataframe,其中有三个计算字段,由下面的apply语句添加: dataset['calculated_field'] = dataset.apply( lambda row: calculation_function( row['field1'], row['field2'] ), axis = 1 ) resultset = dataset.groupby(['grou

我第一次和熊猫一起工作,我在聚合方面遇到了一些问题。我有一个dataframe,其中有三个计算字段,由下面的apply语句添加:

dataset['calculated_field'] = dataset.apply(
    lambda row: calculation_function(
        row['field1'],
        row['field2']
    ),
    axis = 1
)
resultset = dataset.groupby(['grouping_field'])[['calculated_field','calculated_field_2','calculated_field_3']].mean()
计算出的字段是布尔值,但带有一个catch。它们可以包含空值

我试图找到布尔列的平均值,每个平均值忽略该列的空字段

我试过这样的方法:

dataset['calculated_field'] = dataset.apply(
    lambda row: calculation_function(
        row['field1'],
        row['field2']
    ),
    axis = 1
)
resultset = dataset.groupby(['grouping_field'])[['calculated_field','calculated_field_2','calculated_field_3']].mean()
问题在于,由于True/False/None布尔值是“object”类型,pandas会将列完全作为一个对象删除

但是,我无法将该列转换为bool,因为它使空值为“False”

我还尝试了长路由,为每个聚合创建了3个独立的数据帧,因此我可以删除空值并转换为bool(可以聚合):

这给了我正在寻找的数据,但是在三个独立的数据帧中


有没有一种方法可以得到一个数据帧,每个列的平均值忽略空值?

将它们转换为数字列。
None
将变为
NaN
True
s变为
1
False
s变为
0
。转换整个数据帧的一种方便方法是使用
pd.to\u numeric
,将
errors
参数设置为
ignore
。这将保留分组列,因为它将在继续移动时出错

考虑数据帧
df

df = pd.DataFrame(dict(
        gcol=list('aaaabbbb'),
        clc1=[True, False, True, None] * 2,
        clc2=[True, False, True, False] * 2,
        clc3=[True, True, True, True] * 2,
        clc4=[False, None, None, True]* 2
    ))
这就是转换为数字的过程

df.apply(pd.to_numeric, errors='ignore')

   clc1   clc2  clc3  clc4 gcol
0   1.0   True  True   0.0    a
1   0.0  False  True   NaN    a
2   1.0   True  True   NaN    a
3   NaN  False  True   1.0    a
4   1.0   True  True   0.0    b
5   0.0  False  True   NaN    b
6   1.0   True  True   NaN    b
7   NaN  False  True   1.0    b
将其与后续的
groupby
一起使用应该可以得到您想要的

df.apply(pd.to_numeric, errors='ignore').groupby('gcol').mean()

          clc1  clc2  clc3  clc4
gcol                            
a     0.666667   0.5   1.0   0.5
b     0.666667   0.5   1.0   0.5

数字转换正是所需要的。谢谢你的帮助!