11 Pandas的axis参数怎么理解

2022-11-06  本文已影响0人  Viterbi

11 Pandas的axis参数怎么理解?

按哪个axis,就是这个axis要动起来(类似被for遍历),其它的axis保持不动

pandas 底层使用numpy,所以对pandas操作,同时操作一列或者一行效率会很高;

import pandas as pd
import numpy as np

df = pd.DataFrame(
    np.arange(12).reshape(3,4),
    columns=['A', 'B', 'C', 'D']
)

df
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11

1、单列drop,就是删除某一列

# 代表的就是删除某列
df.drop("A", axis=1)
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
B C D
0 1 2 3
1 5 6 7
2 9 10 11

2、单行drop,就是删除某一行

df
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# 代表的就是删除某行
df.drop(1, axis=0)
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D
0 0 1 2 3
2 8 9 10 11

3、按axis=0/index执行mean聚合操作

反直觉:输出的不是每行的结果,而是每列的结果

df
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# axis=0 or axis=index
df.mean(axis=0)


    A    4.0
    B    5.0
    C    6.0
    D    7.0
    dtype: float64

指定了按哪个axis,就是这个axis要动起来(类似被for遍历),其它的axis保持不动

4、按axis=1/columns执行mean聚合操作

反直觉:输出的不是每行的结果,而是每列的结果

df
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# axis=1 or axis=columns
df.mean(axis=1)




    0    1.5
    1    5.5
    2    9.5
    dtype: float64

指定了按哪个axis,就是这个axis要动起来(类似被for遍历),其它的axis保持不动

5、再次举例,加深理解

def get_sum_value(x):
    return x["A"] + x["B"] + x["C"] + x["D"]

df["sum_value"] = df.apply(get_sum_value, axis=1)

df
.dataframe tbody tr th:only-of-type { vertical-align: middle; } <pre><code>.dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </code></pre>
A B C D sum_value
0 0 1 2 3 6
1 4 5 6 7 22
2 8 9 10 11 38

指定了按哪个axis,就是这个axis要动起来(类似被for遍历),其它的axis保持不动

本文使用 文章同步助手 同步

上一篇 下一篇

猜你喜欢

热点阅读