简体   繁体   中英

Reconstructing numpy array after applying function to columns

Say I have a numpy array

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:

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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