Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I quickly create a numpy or pandas 2D array with both axis in a range and the values a product?

The title is more complicated than I was expecting, but I am basically looking for a quick way to make a multiplication table that starts at abitraty integers for both X and Y axises.

My output would be similar to this for X being a range of (5, 12, 1) and Y being a range of (20, 25, 1)

       5      6      7      8      9      10     11
20    100    120    140    160    180    200    220
21    105    126    147    168    189    210    231
22    110    132    154    176    198    220    242
23    115    138    161    184    207    230    253
24    120    144    168    192    216    240    264

I've found this answer which looks similar, but is for indexes. It doesn't seem to do the multiplication I'm looking for.

like image 764
NumpyConfusesMe Avatar asked Nov 30 '25 04:11

NumpyConfusesMe


1 Answers

NumPy broadcasting for pandas!

row = np.arange(20,25)
col = np.arange(5,12)
df = pd.DataFrame(row[:,None]*col,index=row,columns=col)

Sample run -

In [224]: row = np.arange(20,25)

In [225]: col = np.arange(5,12)

In [226]: pd.DataFrame(row[:,None]*col,index=row,columns=col)
Out[226]: 
     5    6    7    8    9    10   11
20  100  120  140  160  180  200  220
21  105  126  147  168  189  210  231
22  110  132  154  176  198  220  242
23  115  138  161  184  207  230  253
24  120  144  168  192  216  240  264
like image 131
Divakar Avatar answered Dec 02 '25 17:12

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!