Matrix of all possible multiplicable results from two lists in a dataframe

I have two lists and I'm trying to create a matrix of all possible multiplication results in a dataframe using pandas .

Lists:

 >>> L1 [8, 1, 4, 2, 7, 5] >>> L2 [5, 3, 9, 1, 2, 6] 

I multiplied each element from L1 by each element from L2 , as follows, to formulate all possible results:

 >>> [[a*b] for a in L1 for b in L2] [[40], [24], [72], [8], [16], [48], [5], [3], [9], [1], [2], [6], [20], [12], [36], [4], [8], [24], [10], [6], [18], [2], [4], [12], [35], [21], [63], [7], [14], [42], [25], [15], [45], [5], [10], [30]] 

Expected Result / Goal:

My goal is to represent these values ​​as a matrix using pandas , but I'm not sure where to start. The first item in the lists is assigned a column / row name of 0-5 .

For instance:

The df matrix should look something like this:

  0 1 2 3 4 5 0 40 5 20 10 35 25 1 24 3 12 6 21 15 2 72 9 36 18 63 45 3 8 1 4 2 7 5 4 16 2 8 4 14 10 5 48 6 24 12 42 30 
+5
source share
2 answers

You can consider the solution with numpy.outer :

 In [879]: pd.DataFrame(np.outer(L2, L1)) Out[879]: 0 1 2 3 4 5 0 40 5 20 10 35 25 1 24 3 12 6 21 15 2 72 9 36 18 63 45 3 8 1 4 2 7 5 4 16 2 8 4 14 10 5 48 6 24 12 42 30 

Performance

Setup:

 x = np.random.choice(26, 1000) y = np.random.choice(26, 1000) %timeit pd.DataFrame([[a*b for b in x] for a in y]) # Willem Van Onsem solution %timeit pd.DataFrame(np.outer(y, x)) # Proposed in this post 

Results:

 1 loop, best of 3: 566 ms per loop 100 loops, best of 3: 3.75 ms per loop 

Numpy's solution is 150 times faster than list comprehension.

+7
source

You can use nested list comprehension:

 pd.DataFrame([[a*b for b in L1] for a in L2]) 

This generates:

 >>> pd.DataFrame([[a*b for b in L1] for a in L2]) 0 1 2 3 4 5 0 40 5 20 10 35 25 1 24 3 12 6 21 15 2 72 9 36 18 63 45 3 8 1 4 2 7 5 4 16 2 8 4 14 10 5 48 6 24 12 42 30 

Thus, understanding the external list [... for a in L2] iterates over L2 and assigns values ​​to the variable a . For each such variable, we generate a list (again with a list) with [a*b for b in L1] , where we loop over the values ​​in L1 and generate a list where we multiply the values ​​with a .

+2
source

Source: https://habr.com/ru/post/1270028/


All Articles