Python在Dataframe中计算Null而不是Null值

时间:2016-04-28 12:47:53

标签: python pandas

我有一个数据框

Date  Name
1995  Harry
1995  John
1997  NaN
1995  NaN
1998  Nina
1998  NaN
1997  Carrie

我需要计算每个日期的NaN /(不是NaN)值。所以输出应该是

Date Nan/NaN+notNaN
1995 1/3
1997 1/2
1998 1/2

我正在尝试 df.groupby(['Date']).agg({'Name' : 'count'}) 但我可以这样做吗 df.groupby(['Date']).agg({'df.Name.isnull()' : 'count'})或者像这样??

1 个答案:

答案 0 :(得分:3)

这样的事情:

In [52]: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum(), 'Date': 'count'})
Out[52]:
      Name  Date
Date
1995     1     3
1997     1     2
1998     1     2

或者你可以这样做:

In [60]: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum().astype(str) + '/' + str(x.size)})
Out[60]:
     Name
Date
1995  1/3
1997  1/2
1998  1/2

format

In [62]: df.groupby('Date').agg({'Name': lambda x: '{}/{}'.format(x.isnull().sum(), len(x))})
Out[62]:
     Name
Date
1995  1/3
1997  1/2
1998  1/2