
In this post, we will learn how to use axis=0 and axis=1 in pandas. Almost all methods and functions in pandas has the axis parameter and knowing how to use it is very important for doing analysis. I will explain it with concrete examples so that you can understand it very well without any worries . So let’s get started.
Axis in Pandas –
first let’s read a dataset.
import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/online_shoppers.csv"
df = pd.read_csv(url)
df2 = pd.crosstab(index= df['Month'], columns= df['VisitorType'])
df2

Here, we have some data from an online shopping website. And Let’s say we want to add these numbers vertically and horizontally.
axis = 0 or axis = index –
When we say axis=0 or axis=index, it basically means that we want to do row-wise operation on each columns.

So, if we say
df2.sum(axis=0)

For the New visitor column, it will first add the 55 to 219 then 0, 42, 22 ……. 80. It will do the sum row-wise for the first column, second column and the third column.
axis = 1 or axis= columns –
And when we say axis= 1 or axis=columns, we basically means that we want to do column-wise operation on each rows in the dataframe.

So, when we say
df2.sum(axis=1)

For August, pandas will add ( 55 + 0 + 252= 307) and then for Dec it will add (219 + 42 + 955= 1216 ) and so on. So, Pandas will apply column-wise operation on each rows in the dataframe.
I hope this clarify how axis works in pandas. If you like this post then share it with others and subscribe to our blog for more articles related to pandas below.