Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

How to get Total in crosstab pandas?

I have a df like below, I want to convert this into cross table using below code,

g= list('M'*75)+list('F'*75)
c =list('B'*51)+list('T'*24)+list('B'*49)+list('T'*26)
df=pd.DataFrame({'Gender':g,'City':c})
tbl=pd.crosstab(df['City'],df['Gender'])

cross table:

Gender   F   M
City          
B       49  51
T       26  24

How to get the sum or total values of cross tab result. i.e., 49+51+26+24

So far I used this,

tbl.sum().sum()

Expected O/P:

150

Even though I got the required result, I'm wondering Do I need to use two chain sum functions here for this problem?

Upvotes: 1

Views: 952

Answers (1)

jezrael
jezrael

Reputation: 862741

I think not, you can convert DataFrame to numpy array and call numpy.sum with no axis, so it sum all values to scalar:

print (tbl.values.sum())
150

print (np.sum(tbl.values))
150

Upvotes: 1

Related Questions