0

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?

2 Answers 2

1

This is one way:

numpy.core.records.fromarrays([arr['A'], arr['B'], arr['A']*arr['B']], names='A,B,C')

Another way:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.