pandas之axis

为什么 axis=1 有的时候表示行,有的时候表示列?其实,这只是一种错觉。
本质上,
axis=0:表示沿着每一列或行标签\索引值向下执行方法
axis=1:表示沿着每一行或者列标签模向执行对应的方法

axis参数作用方向图示
案例:

[in 1]:frame = DataFrame(np.arange(12).reshape(3, 4),  index=list("123"), columns=list("abcd"))
[in 2]:frame
[out 2]:
	a  b   c   d
1  	0  1   2   3
2  	4  5   6   7
3  	8  9  10  11

# 第一种情况,对 Dataframe使用sum方法
# 当 axis 为默认值0 时,对整列求和
[in 5]:frame.sum()
[out 5]:
a    12
b    15
c    18
d    21
dtype: int64

# 当 axis=1时,对整行求和
[in 6]:frame.sum(axis=1)
Out[6]: 
1     6
2    22
3    38
dtype: int64

# 第二种情况,对 Dataframe使用drop方法
# 当 axis 为默认值0 时,看起来是删除整行。
""" 实际表示的是,对该标签所在的每一个数据进行 列操作"""
[in 3]:frame.drop('2')
[out 3]:
   a  b   c   d
1  0  1   2   3
3  8  9  10  11

# 当 axis=1时,看起来是删除整列。
"""实际表示的是,对该标签所在的每一个数据进 行列操作"""
[in 4]:frame.drop('c', axis=1)
[out 4]:
   a  b   d
1  0  1   3
2  4  5   7
3  8  9  11


发布了13 篇原创文章 · 获赞 6 · 访问量 527

猜你喜欢

转载自blog.csdn.net/ljr_123/article/details/104670960