How can a specific operation be applied row wise or column wise in Pandas Python?

PythonServer Side ProgrammingProgramming

It may sometimes be required to apply certain functions along the axes of a dataframe. The axis can be specified, otherwise the default axis is considered as column-wise, where every column is considered as an array.

If the axis is specified, then the operations are performed row-wise on the data.

The ‘apply’ function can be used in conjunction with the dot operator on the dataframe. Let us see an example −

Example

 Live Demo

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])}
print("The dataframe is :")
my_df = pd.DataFrame(my_data)
print(my_df)
print("The description of data is :")
print(my_df.apply(np.mean))

Output

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
The description of data is :
Age    47.200
value  46.554
dtype: float64

Explanation

  • The required libraries are imported, and given alias names for ease of use.

  • Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure.

  • This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library

  • The dataframe is printed on the console.

  • We are looking at getting all the information about the data.

  • The ‘describe’ function is called on the dataframe.

  • The description is printed on the console.

raja
Published on 10-Dec-2020 13:28:19
Advertisements