1

I want to know that how can I count elements in a column of dataframe and know what element has the highest count?

For example, I have this dataframe:

 sample target 0 a 0 1 b 0 2 c 0 3 d 1 4 e 1 5 f 1 6 g 0 

At the first step, I have to count target column: I want something that give me how many 0 or 1 is in target column and at the next step I want to know what target has the greater amount of count. In this example the answer is 0, my question is how can I get the true target. In this case, I need a code to give me 0 as the greatest amount of count for target column.

2

2 Answers 2

2

You can use groupby in pandas

>>> df = pd.DataFrame({'sample':['a','b','c','d','e','f','g'],'target':[0,0,0,1,1,1,0]}) >>> df.groupby(['target']).count() sample target 0 4 1 3 >>> 

If you want to get the max you can use max() function on the grouped dataframe. Or if you want to get the index(target in your case) you can use idxmax() function.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much brother, its working very well.
@LMKR from my experience it helps if add a comment saying please accept if it helps for you just after adding the answer.
1

If I understand the question correctly, you are just interested in the working with the target column. In that case, you can simply use value_counts() method:

>>> df = pd.DataFrame({'sample':['a','b','c','d','e','f','g'],'target':[0,0,0,1,1,1,0]}) >>> df sample target 0 a 0 1 b 0 2 c 0 3 d 1 4 e 1 5 f 1 6 g 0 >>> df['target'].value_counts(ascending=False) #output 0 4 1 3 Name: target, dtype: int64 #find the target class with max count >>> df['target'].value_counts(ascending=False).index[0] 0 #find the max count >>> df['target'].value_counts(ascending=False).max() 4 

This method is not gonna work if you want to find max counts within samples. In that case, groupby method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.