简体   繁体   中英

Pandas: groupby then count based on condition gives NaN

I have the following dataset:

+----+------+
| ID | Type |
+----+------+
| a  | New  |
+----+------+
| b  | Old  |
+----+------+
| b  | Old  |
+----+------+
| b  | New  |
+----+------+
| c  | Old  |
+----+------+

I'm trying to group by ID, and then count the number of New occurences for each group. So for example I would have a=1 , b=2 , and c=0 .

Here's what I've tried:

df['NewAmount'] = df.groupby('ID')['Type'].apply(
    lambda x: x[x == 'New'].count())

And I get this:

+----+------+----------+
| ID | Type | NewAmount|
+----+------+----------+
| a  | New  | NaN      |
+----+------+----------+
| b  | Old  | NaN      |
+----+------+----------+
| b  | Old  | NaN      |
+----+------+----------+
| b  | New  | NaN      |
+----+------+----------+
| c  | Old  | NaN      |
+----+------+----------+

You should try with transform

df['out'] = df['Type'].eq('New').groupby(df['ID']).transform('sum')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM