I have a python numpy ndarray with 2 numeric fields. Want to add a third field to it which is just the multiplication of the two. The two columns are named as "A" and "B" and I want the third column to be called "C". How should I proceed?
This is one way :
numpy.core.records.fromarrays([arr['A'], arr['B'], arr['A']*arr['B']], names='A,B,C')
numpy.lib.recfunctions.append_fields(arr, 'C', arr['A']*arr['B'])
Note that these will return a new array containing all the columns. There's no way to add a column in-place.
works too but more verbose
import numpy as np
my_array = np.random.random_sample((10,2))
array_c = my_array[:,0]* my_array[:,1]
dt = [('A', float), ('B', float), ('C', float)]
my_array = np.column_stack((my_array, array_c)).astype(dt)
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.