2

I have following dataframe:

    name    gender    count
0     A      M         3
1     A      F         2
2     A      Nan       3
3     B      NaN       2
4     C      F         4
5     D      M         5
6     D      Nan       5

I would like to build a resulting dataframe df1 which deletes that last row of group of name attribute if the count of that group is greater than 1. For eq- name A is present 3 times, hence the last row containing A should be removed. B and C are only present once, hence the rows containing them should be retained.

Resulting dataframe df1 should be like this:

     name    gender    count
0     A      M         3
1     A      F         2
2     B      NaN       2
3     C      F         4
4     D      M         5

Please advice.

2 Answers 2

2

Use

In [4598]: (df.groupby('name').apply(lambda x: x.iloc[:-1] if len(x)>1 else x)
              .reset_index(drop=True))
Out[4598]:
  name gender  count
0    A      M      3
1    A      F      2
2    B    NaN      2
3    C      F      4
4    D      M      5
Sign up to request clarification or add additional context in comments.

Comments

1

Using groupby + head:

g = df.groupby('name', as_index=False, group_keys=False)\
          .apply(lambda x: x.head(-1) if x.shape[0] > 1 else x)
print(g)
  name gender  count
0    A      M      3
1    A      F      2
3    B    NaN      2
4    C      F      4
5    D      M      5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.