简体   繁体   English

将函数应用于列后重建numpy数组

[英]Reconstructing numpy array after applying function to columns

Say I have a numpy array 说我有一个numpy数组

import numpy as np
>>> a = np.array([[1, 2], 
                  [3, 4]])

and I want to extract each column and apply a function to it like so 我想提取每一列并像这样应用一个函数

>>> a_col_1 = a[:, 0]
array([1, 3])
>>> new_col_1 = tranform(a_col_1)
array([[1, 1], 
       [3, 3]])

>>> a_col_2 = a[:, 1]
array([2, 4])
>>> new_col_2 = tranform(a_col_2)
array([[2, 2], 
       [4, 4]])

and then somehow reconstruct the original array with its new expanded values in place of the old singe values, like so: 然后以某种方式用新的扩展值代替原始的singe值来重构原始数组,如下所示:

array([[1, 1, 2, 2], 
       [3, 3, 4, 4]])

Is there a convenient numpy way to do this? 有没有方便的方法来做到这一点?

This is actually super easy! 这实际上是超级容易的! Some quick experimentation with the numpy.concatenate function found that I can achieve the results I need with np.concatenate([new_col_1, new_col_2], axis=1) . 使用numpy.concatenate函数进行的一些快速实验发现,使用np.concatenate([new_col_1, new_col_2], axis=1)可以达到所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM