numpy数组按某一维度相加_Python数据分析之NumPy(高级篇)

96b381ea02ee48d2994d37c720a65216

一些更高级的ndarray处理

where和一些其他的逻辑运算

np.where(cond,x,y):满足条件(cond)输出x,不满足输出y

x_arr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])y_arr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])cond = np.array([True, False, True, True, False])print(np.where(cond, x_arr, y_arr))
[ 1.1  2.2  1.3  1.4  2.5]
arr = np.random.randn(4,4)print(arr)print(np.where(arr > 0, 2, -2))print(np.where(arr > 0, 2, arr))
[[ -1.10484247e+00  -3.82422727e-01  -3.24361549e-01   1.21286234e+00] [  1.54499855e-01  -4.77728163e-04   1.44621074e+00  -2.64241611e-03] [  1.36394862e+00   6.96638259e-02  -2.75237740e-01  -3.32892881e-01] [ -1.37165175e+00   1.79997993e-01  -1.13509664e-01   1.88373639e+00]][[-2 -2 -2  2] [ 2 -2  2 -2] [ 2  2 -2 -2] [-2  2 -2  2]][[ -1.10484247e+00  -3.82422727e-01  -3.24361549e-01   2.00000000e+00] [  2.00000000e+00  -4.77728163e-04   2.00000000e+00  -2.64241611e-03] [  2.00000000e+00   2.00000000e+00  -2.75237740e-01  -3.32892881e-01] [ -1.37165175e+00   2.00000000e+00  -1.13509664e-01   2.00000000e+00]]

np.where可以嵌套使用

cond_1 = np.array([True, False, True, True, False])cond_2 = np.array([False, True, False, True, False])result = np.where(cond_1 & cond_2, 0,           np.where(cond_1, 1, np.where(cond_2, 2, 3)))print(result)
[1 2 1 0 3]
arr = np.random.randn(10)print(arr)print((arr > 0).sum()) #数组中大于0的数相加
[ 0.27350655 -1.51093462  0.26835915 -0.45991855  1.34450904 -1.86871203  0.04308971  1.69640444 -0.02191351 -0.43875275]5
bools = np.array([False, False, True, False])print(bools.any()) # 有一个为True则返回Trueprint(bools.all()) # 有一个为False则返回False
TrueFalse

reshape(数组变形)

numpy可以很容易地把一维数组转成二维数组,三维数组。

import numpy as nparr = np.arange(8)print("(4,2):", arr.reshape((4,2)))print()print("(2,2,2):", arr.reshape((2,2,2)))
(4,2): [[0 1] [2 3] [4 5] [6 7]](2,2,2): [[[0 1]  [2 3]] [[4 5]  [6 7]]]

-1( 维度自动推算)

如果我们在某一个维度上写上-1,numpy会帮我们自动推导出正确的维度

arr = np.arange(15)print(arr.reshape((5,-1)))print(arr.reshape((5,-1)).shape)
[[ 0  1  2] [ 3  4  5] [ 6  7  8] [ 9 10 11] [12 13 14]](5, 3)

ravel(拉平数组)

# 高维数组用ravel来拉平成为一维数组arr = np.arange(15)print(arr.ravel())
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]

concatenate(连接数组)

arr1 = np.array([[1, 2, 3], [4, 5, 6]])arr2 = np.array([[7, 8, 9], [10, 11, 12]])print(np.concatenate([arr1
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值