Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can a specific operation be applied row wise or column wise in Pandas Python?
In Pandas, you can apply operations to a DataFrame either row-wise or column-wise using the apply() function. By default, operations are applied column-wise (axis=0), but you can specify the axis parameter to control the direction.
Column-wise Operations (Default)
When no axis is specified, operations are applied to each column ?
import pandas as pd
import numpy as np
my_data = {'Age': pd.Series([45, 67, 89, 12, 23]),
'value': pd.Series([8.79, 23.24, 31.98, 78.56, 90.20])}
my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)
print("\nColumn-wise mean:")
print(my_df.apply(np.mean))
The dataframe is: Age value 0 45 8.79 1 67 23.24 2 89 31.98 3 12 78.56 4 23 90.20 Column-wise mean: Age 47.200 value 46.554 dtype: float64
Row-wise Operations
To apply operations row-wise, set axis=1 ?
import pandas as pd
import numpy as np
my_data = {'Age': pd.Series([45, 67, 89, 12, 23]),
'value': pd.Series([8.79, 23.24, 31.98, 78.56, 90.20])}
my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)
print("\nRow-wise mean:")
print(my_df.apply(np.mean, axis=1))
print("\nRow-wise sum:")
print(my_df.apply(np.sum, axis=1))
The dataframe is: Age value 0 45 8.79 1 67 23.24 2 89 31.98 3 12 78.56 4 23 90.20 Row-wise mean: 0 26.895 1 45.120 2 60.490 3 45.280 4 56.600 dtype: float64 Row-wise sum: 0 53.79 1 90.24 2 120.98 3 90.56 4 113.20 dtype: float64
Custom Functions
You can also apply custom functions using lambda or defined functions ?
import pandas as pd
import numpy as np
my_data = {'Age': pd.Series([45, 67, 89, 12, 23]),
'value': pd.Series([8.79, 23.24, 31.98, 78.56, 90.20])}
my_df = pd.DataFrame(my_data)
# Custom function to find range (max - min)
def find_range(x):
return x.max() - x.min()
print("Column-wise range:")
print(my_df.apply(find_range))
print("\nRow-wise range:")
print(my_df.apply(lambda x: x.max() - x.min(), axis=1))
Column-wise range: Age 77.00 value 81.41 dtype: float64 Row-wise range: 0 36.21 1 43.76 2 57.02 3 66.56 4 67.20 dtype: float64
Axis Parameter Summary
| Parameter | Direction | Description |
|---|---|---|
axis=0 (default) |
Column-wise | Apply function to each column |
axis=1 |
Row-wise | Apply function to each row |
Conclusion
Use apply() with axis=0 for column-wise operations and axis=1 for row-wise operations. This flexibility allows you to perform statistical operations or custom functions across either dimension of your DataFrame.
Advertisements
