【问题标题】:fill a 2D array using a for loop using other 2D arrays使用 for 循环填充 2D 数组,使用其他 2D 数组
【发布时间】:2019-10-16 22:00:00
【问题描述】:

我有两个二维 numpy 数组 a(N,D) b(M,D),我想填充第三个数组 c(M,D*N),它是 a 和 b 的函数。如果 N= 2 和 D=3 我希望 c 如下:

c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 

c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2] 

如何使用循环(for、while)填充 c?

【问题讨论】:

  • 为什么不使用矢量化工具?使用数组时,您可能更喜欢效率?
  • 矢量化工具是什么意思?
  • 类似于发布的答案。

标签: python-3.x loops numpy indexing


【解决方案1】:

这是一种利用 broadcasting 的矢量化方式,旨在提高性能 -

bs = b*np.std(b,axis=0,keepdims=True)
c_out = (bs[:,None,:]+a).reshape(len(b),-1)

示例运行 -

In [43]: N,M,D = 2,4,3
    ...: np.random.seed(0)
    ...: a = np.random.rand(N,D)
    ...: b = np.random.rand(M,D)
    ...: c = np.zeros((M,D*N))
    ...: 
    ...: c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
    ...: c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
    ...: c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 
    ...: 
    ...: c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
    ...: c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
    ...: c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]

In [44]: c
Out[44]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])

In [45]: bs = b*np.std(b,axis=0,keepdims=True)
    ...: c_out = (bs[:,None,:]+a).reshape(len(b),-1)

In [46]: c_out
Out[46]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])

【讨论】:

  • 好的,谢谢,这会占用更多内存吗?因为以后想用大尺寸
  • @ElenaPopa 这将占用获得最终输出所需的内存。
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2022-01-24
  • 1970-01-01
  • 2021-05-21
  • 2014-06-22
  • 2014-04-09
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多