Python 熊猫:忽略NaN的平均值的函数在哪里

Python 熊猫:忽略NaN的平均值的函数在哪里,python,pandas,Python,Pandas,我有一些数据框,我想在这些数据框上应用groupby: dftest = df1.append(test2).set_index('date') doWhat = {'foo' : np.sum, 'bar': np.sum, 'employment_total' : np.mean} employment\u total在某些地方是NaN,但不是在所有地方: >>> sum(np.isnan(dftest.employment_total)) 404394 >>

我有一些数据框,我想在这些数据框上应用groupby:

dftest = df1.append(test2).set_index('date')
doWhat = {'foo' : np.sum, 'bar': np.sum, 'employment_total' : np.mean}
employment\u total
在某些地方是
NaN
,但不是在所有地方:

>>> sum(np.isnan(dftest.employment_total))
404394
>>> sum(np.isnan(dftest.employment_total) == False)
6864
然而,当我创建月平均值时,它将是
NaN
无处不在-我猜是因为我使用的是
np.mean

aggASS = dftest.groupby(['state', pd.TimeGrouper("M", label='left'), 'status']).agg(doWhat)
>>> aggASS.loc[np.isnan(aggASS.employment_total) == False]
Empty DataFrame
Columns: [shopping_weighted, employment_total]
Index: []

我需要使用
doWhat
,因为我对不同的列使用不同的聚合度量。我试图找到在计算前删除
NaN
pandas.mean
函数,但找不到它。它在哪里?

您可以将mean参数作为字符串
'mean'
传递,它将使用默认情况下跳过nans的字符串

import pandas as pd

df = pd.DataFrame(data={'x':[1, 2, 3, 4, pd.np.nan], 'y':['a', 'a', 'a', 'b', 'b']})

funcs = {'x':'mean'}

print(df.groupby('y').agg(funcs))
#    x
# y   
# a  2
# b  4

您可以使用pandas系列版本:
doWhat={'foo':np.sum,'bar':np.sum,'employment_total':pd.series.mean}
您可能只需要
doWhat={'foo':np.sum,'bar':np.sum,'employment_total':mean}就可以逃脱了
这有
skipna
参数,默认情况下为True,因此将跳过
NaN
值。因此,首选顶级panda
isnull
notnull
而不是numpy版本
sum(dftest.employment\u total.isnull())