Pandas DataFrame count()

Pandas

We can count number of in rows or columns by using count().

import pandas as pd 
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
         'ID':[1,2,3,4,5,6],
         'MATH':[80,40,70,70,70,30],
         'ENGLISH':[80,70,40,50,60,30]}
my_data = pd.DataFrame(data=my_dict)
print(my_data.count())
Output
NAME       6
ID         6
MATH       6
ENGLISH    6

Using axis

Axis of Two dimensional array We will use option axis=0 ( default ) by adding to above code.

( The last line is only changed )
print(my_data.count(axis=0))
Output is here
NAME       6
ID         6
MATH       6
ENGLISH    6
Now let us use axis=1
print(my_data.count(axis=1))
Output
0    4
1    4
2    4
3    4
4    4
5    4
Handling NA data
import numpy as np
import pandas as pd 
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
         'ID':[1,2,3,4,5,6],
         'MATH':[80,40,70,70,70,30],
         'ENGLISH':[80,70,np.nan,50,60,30]}
my_data = pd.DataFrame(data=my_dict)
print(my_data.count(axis=1))
Output
0    4
1    4
2    3
3    4
4    4
5    4
count() has not considered np.nan so the third row is 3.

lavel option

We can specify the level option and get the data
import numpy as np
import pandas as pd 
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
         'ID':[1,2,3,4,5,6],
         'MATH':[80,40,70,70,70,30],
         'ENGLISH':[80,70,np.nan,50,60,30]}
my_data = pd.DataFrame(data=my_dict)
my_data.set_index(['NAME','ID']).count(level='NAME')
Output
	MATH	ENGLISH
NAME		
Alex	1	0
Jack	1	1
King	1	1
Raju	1	1
Ravi	1	1
Ron	1	1
Pandas Plotting graphs Filtering of Data


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer