Axis Argument in pandas DataFrames in Python (2 Examples)
In this Python tutorial you’ll learn how to use the axis argument in pandas DataFrames.
Creating Exemplifying Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
my_df = pd.DataFrame({'A':range(1, 5), # Construct new pandas DataFrame 'B':[5, 5, 1, 3], 'C':range(15, 11, - 1)}) print(my_df) # A B C # 0 1 5 15 # 1 2 5 14 # 2 3 1 13 # 3 4 3 12 |
my_df = pd.DataFrame({'A':range(1, 5), # Construct new pandas DataFrame 'B':[5, 5, 1, 3], 'C':range(15, 11, - 1)}) print(my_df) # A B C # 0 1 5 15 # 1 2 5 14 # 2 3 1 13 # 3 4 3 12
Example 1: Calculate Row-Wise Sum by Specifying axis = 1
print(my_df.sum(axis = 1)) # Sum of each row # 0 21 # 1 21 # 2 17 # 3 19 # dtype: int64 |
print(my_df.sum(axis = 1)) # Sum of each row # 0 21 # 1 21 # 2 17 # 3 19 # dtype: int64
Example 2: Calculate Column-Wise Sum by Specifying axis = 0
print(data.sum(axis = 0)) # Sum of each column # x1 21 # x2 37 # x3 28 # dtype: int64 |
print(data.sum(axis = 0)) # Sum of each column # x1 21 # x2 37 # x3 28 # dtype: int64
Further Resources & Related Articles
Furthermore, you might read some of the other Python programming posts on this website.