How to add two columns of a numpy array?
I have two NumPy
arrays with the same number of rows, but I want to add specific columns.
I tried the following:
src_array[:, 3] += column_array_to_add[:, 0]
However, that doesn't even interpret. What is the correct way to do this in NumPy
? I want to be able to do it with both integers and strings.
Edit: A short, self-contained script for testing
import numpy
src = numpy.array([["a", "b"], ["c", "d"], ["e", "f"]])
src2 = numpy.array([["x"], ["y"], ["z"]])
src[:, 1] += src2[:, 0]
print src
exit()
This script returns the following error:
src[:, 1] += src2[:, 0]
TypeError: unsupported operand type(s) for +=: 'numpy.ndarray' and 'numpy.ndarray'
Does something like this work?
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
result
>>> x
array([[1, 2],
[3, 4]])
>>> y
array([[5, 6],
[7, 8]])
>>> x[:,1] + y[:,1]
array([ 8, 12])
>>> x[:, 1] += y[:, 1] # using +=
>>> x[:, 1]
array([ 8, 12])
Update:
I think this should work for you:
src = np.array([["a", "b"], ["c", "d"], ["e", "f"]], dtype='|S8')
src2 = np.array([["x"], ["y"], ["z"]], dtype='|S8')
def add_columns(x, y):
return [a + b for a,b in zip(x, y)]
def update_array(source_array, col_num, add_col):
temp_col = add_columns(source_array[:, col_num], add_col)
source_array[:, col_num] = temp_col
return source_array
Result:
>>> update_array(src, 1, src2[:,0])
array([['a', 'bx'],
['c', 'dy'],
['e', 'fz']],
dtype='|S8')