Home >Backend Development >Python Tutorial >What Does the `axis` Parameter Mean in Pandas Functions?

What Does the `axis` Parameter Mean in Pandas Functions?

DDD
DDDOriginal
2024-11-04 12:21:30245browse

What Does the `axis` Parameter Mean in Pandas Functions?

Axis in Pandas: Understanding Its Meaning

In Pandas, the axis keyword parameter in functions such as mean() defines along which axis the operation is performed.

Consider the following code:

import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))

This creates a dataframe:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|
+------------+---------+--------+

Now, let's calculate the mean along the rows (axis=1):

dff.mean(axis=1)

This gives the following result:

0    1.074821
dtype: float64

Counterintuitively, the expected result is:

A    0.626386
B    1.523255
dtype: float64

Understanding the Axis Parameter

The axis parameter specifies the direction in which the operation is performed.

  • axis=0: Operates along the rows (index) of the dataframe.
  • axis=1: Operates along the columns (columns) of the dataframe.

In the given example, the mean is calculated along the columns (axis=1), resulting in a single value for each row.

Visualizing the Axis

To visualize the axis, consider the following diagram:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
             |         |
             | axis=0  |
             ↓         ↓

The red arrow represents axis=1, which operates along the columns. The green arrow represents axis=0, which operates along the rows.

The above is the detailed content of What Does the `axis` Parameter Mean in Pandas Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn