numpy 和 pandas 计算中 axis 的一些理解

对于 pandas 中的一些计算 computation 的问题中使用到的 axis,并非是在 axis 方向上进行计算,而是在 axis 方向上传播,你会发现,运算结束,原先的那个 axis 维度消失了

不过对于 apply,, df.dropna() 之类的问题 axis 还是理解为 along the axis 比较好

搬运 stackoverflow 上的一些解释:

axis=0 means each row as a bulk, we only can manipulate DataFrame inter-row instead of inner-row. axis=1 means each column as a bulk, we only can manipulate DataFrame inter-column instead of inner-column. So if you use df.drop(“A”, axis = 1), it will drop a whole column. – Belter

对于 np.sum 中的 axis

b = np.arange(24).reshape(2,3,4)
b
--------------------------
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
b.sum(axis=0)

-------------------------
array([[12, 14, 16, 18],
       [20, 22, 24, 26],
       [28, 30, 32, 34]])

代码解释

a = np.zeros(3,4)
for i in range(3):
    for j in range(4):
        a[i,j] += a[:,i,j].sum()

对于 np.concatenate 中的 axis

arr = np.arange(12).reshape((3, 4))
arr
----------------------------------
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
np.concatenate([arr, arr], axis=0)
-----------------------------------------
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
np.concatenate([arr, arr], axis=1)
-----------------------------------------
array([[ 0,  1,  2,  3,  0,  1,  2,  3],
       [ 4,  5,  6,  7,  4,  5,  6,  7],
       [ 8,  9, 10, 11,  8,  9, 10, 11]])

对 axis=0 的 concatenate 操作,在第一个轴进行了合并,由原来的 (3,4) --> (6,4)

对 axis=1 的 concatenate 操作,在第二个轴进行了合并,由原来的 (3,4) --> (3,8)

pandas 中的 pd.concat() 同理

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值