What is the role of keepdims in Numpy (Python)?

后端 未结 4 1176
北海茫月
北海茫月 2021-02-10 10:26

When I use np.sum, I encountered a parameter called keepdims. After looking up the docs, I still cannot understand the meaning of keepdims

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-10 11:09

    You can keep the dimension with "keepdims=True" if you sum a matrix For example:

    import numpy as np
    x  = np.array([[1,2,3],[4,5,6]])
    x.shape
    # (2, 3)
    
    np.sum(x, keepdims=True).shape
    # (1, 1)
    np.sum(x, keepdims=True)
    # array([[21]]) <---the reault is still a 1x1 array
    
    np.sum(x, keepdims=False).shape
    # ()
    np.sum(x, keepdims=False)
    # 21 <--- the result is an integer with no dimesion
    

提交回复
热议问题