How to Use axis=0 and axis=1 in Pandas?
In this article, we will discuss how to use axis=0 and axis=1 in pandas using Python.
Sometimes we need to do operations only on rows, and sometimes only on columns, in such situations, we specify the axis parameter. In this article, let’s see a few examples to know when and how to use the axis parameter. In pandas axis = 0 refers to horizontal axis or rows and axis = 1 refers to vertical axis or columns.
AXIS =0
When the axis is set to zero while performing a specific action, the action is performed on rows that satisfy the condition.
Dataset Used:
Example: Using axis=0
Python3
import pandas as pd
df = pd.read_csv( 'hiring.csv' )
df = df.drop([ 0 , 3 ], axis = 0 )
df.head()
|
Output:
Example: Using axis=0
Python3
import pandas as pd
df = pd.DataFrame([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ],
[ 7 , 8 , 9 ], [ 10 , 11 , 12 ]],
columns = [ 'a' , 'b' , 'c' ])
print (df)
df.mean(axis = 'rows' )
|
Output:
AXIS=1
When the axis is set to one while performing a specific action, the action is performed on column(s) that satisfy the condition.
Example: Using axis=1
Python3
import pandas as pd
df = pd.read_csv( 'hiring.csv' )
df = df.drop([ 'experience' ], axis = 1 )
df.head()
|
Output:
Example: Using axis=1
Python3
import pandas as pd
df = pd.DataFrame([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ],
[ 7 , 8 , 9 ], [ 10 , 11 , 12 ]],
columns = [ 'a' , 'b' , 'c' ])
print (df)
df.mean(axis = 'columns' )
|
Output:
Last Updated :
19 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...