如何只计算pandas数据帧中的特定值

时间:2022-03-24 23:01:48

I have the following pandas dataframe;

我有以下pandas数据帧;

a = [['01', '12345', 'null'], ['02', '78910', '9870'], ['01', '23456', 'null'],['01', '98765', '8760']]

df_a = pd.DataFrame(a, columns=['id', 'order', 'location'])

I need to get a count of how many NULL values (NULL is a string) that occur for each ID. So the result would look like;

我需要计算每个ID发生的NULL值(NULL是一个字符串)的数量。结果看起来像;

id   null_count
01    02

I can get basic counts using a groupby:

我可以使用groupby获得基本计数:

new_df = df_a.groupby(['id', 'location'])['id'].count()

But the results return more than just the NULL values;

但结果返回的不仅仅是NULL值;

id  location
01  8760        1
    null        2
02  9870        1

3 个解决方案

#1


6  

Because in your source dataframe your NULLs are strings 'null', use:

因为在源数据帧中,您的NULL是字符串'null',请使用:

df_a.groupby('id')['location'].apply(lambda x: (x=='null').sum())\
    .reset_index(name='null_count')

Output:

输出:

   id  null_count
0  01          2
1  02          0

OR

要么

df_a.query('location == "null"').groupby('id')['location'].size()\
    .reset_index(name='null_count')

Output:

输出:

   id  null_count
0  01           2

#2


5  

Base on your own code , adding .loc notice this is multi index slice ..

基于您自己的代码,添加.loc注意这是多索引切片..

df_a.groupby(['id', 'location'])['id'].count().loc[:,'null']
Out[932]: 
id
01    2
Name: id, dtype: int64

#3


4  

In [16]: df_a.set_index('id')['location'].eq('null').sum(level=0)
Out[16]:
id
01    2.0
02    0.0
Name: location, dtype: float64

#1


6  

Because in your source dataframe your NULLs are strings 'null', use:

因为在源数据帧中,您的NULL是字符串'null',请使用:

df_a.groupby('id')['location'].apply(lambda x: (x=='null').sum())\
    .reset_index(name='null_count')

Output:

输出:

   id  null_count
0  01          2
1  02          0

OR

要么

df_a.query('location == "null"').groupby('id')['location'].size()\
    .reset_index(name='null_count')

Output:

输出:

   id  null_count
0  01           2

#2


5  

Base on your own code , adding .loc notice this is multi index slice ..

基于您自己的代码,添加.loc注意这是多索引切片..

df_a.groupby(['id', 'location'])['id'].count().loc[:,'null']
Out[932]: 
id
01    2
Name: id, dtype: int64

#3


4  

In [16]: df_a.set_index('id')['location'].eq('null').sum(level=0)
Out[16]:
id
01    2.0
02    0.0
Name: location, dtype: float64