1

I have the following pandas dataframe. Each point is combined with 'n' class points of each class, and each combination has a value of 0 or 1. Now for each point, I want to get the class which has the highest number of '0'. Output : Pt.1 - a Pt.2 -b

I have tried with hash table, but its being a bit cumbersome. What can be an elegant pandas dataframe query for this?

+------+-------+-------+--+--+--+
| Pt.  | class | value |  |  |  |
+------+-------+-------+--+--+--+
| Pt.1 | a     |     0 |  |  |  |
| Pt.1 | a     |     0 |  |  |  |
| Pt.1 | a     |     1 |  |  |  |
| Pt.1 | b     |     0 |  |  |  |
| Pt.1 | b     |     1 |  |  |  |
| pt.1 | b     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
|      |       |       |  |  |  |
+------+-------+-------+--+--+--+
2
  • Why is the r tag here? Commented Nov 15, 2017 at 12:45
  • because dataframe operations are similar in r and python Commented Nov 15, 2017 at 13:15

1 Answer 1

1

First filter only 0 rows by boolean indexing and then count by groupby with value_counts which sorts output, so is necessary seelct first index value by indexing:

df = (df[df['value'] == 0].groupby('Pt.')['class']
                          .apply(lambda x: x.value_counts().index[0])
                          .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b

Similar alternative with query for filtering:

df = (df.query("value == 0")
        .groupby('Pt.')['class']
        .apply(lambda x: x.value_counts().index[0])
        .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked perfectly!

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.