简体   繁体   中英

Show Math Addition in two Arrays Python

how do i write a code to show the addition operation between two arrays (row wise), i don't want the result of the addition but want to illustrate the operation. Here is what I have, however my code is not giving me the right output

import numpy as np
Grid = np.random.randint(-50,50, size=(5,4))
iList =np.array([[1, -1, 2, -2]])

result = (Grid.astype(str), iList.astype(str))
print(result)

the output needs to be something to this effect

([3+1 4-1 4+2 5-2] [6+1 9-1 7+2 8-2]

etc.

thank you.

You basically want to apply a function to two numpy arrays of different sizes, making use of numpy's broadcasting capability.

This works:

import numpy as np

grid = np.random.randint(-50, 50, size=(5, 4))
i_list = np.array([[1, -1, 2, -2]])


def sum_text(x: int, y: int):
     return f'{x}+{y}'


# create a ufunc, telling numpy that it takes 2 arguments and returns 1 value
np_sum_text = np.frompyfunc(sum_text, 2, 1)

result = np_sum_text(grid, i_list)
print(result)

Result:

[['46+1' '-27+-1' '35+2' '-3+-2']
 ['-5+1' '6+-1' '2+2' '22+-2']
 ['6+1' '-45+-1' '-21+2' '31+-2']
 ['25+1' '-4+-1' '-24+2' '3+-2']
 ['-32+1' '-10+-1' '-19+2' '28+-2']]

Or maybe you don't need to reuse that function and like one-liners:

print(np.frompyfunc(lambda x, y: f'{x}+{y}', 2, 1)(grid, i_list))

Getting rid of the + before a negative integer is trivial:

def sum_text(x: int, y: int):
     return f'{x}+{y}' if y >= 0 else f'{x}{y}'

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