Loading...

Multiplying a list of (X, Y) combinations


I'm trying to multiply combinations I generated and create a new list out of them.

Here is what I have so far:

import pandas as pd
import itertools

data1 = [[0.1],[0.2],[0.3],[0.5]]

df = pd.DataFrame(data1, columns = ['weights'])

for x in combinations(df['weights'], 2):
    print(x)

>>>
(0.1, 0.2)
(0.1, 0.3)
(0.1, 0.5)
(0.2, 0.3)
(0.2, 0.5)
(0.3, 0.5)
##I want to make a new list that shows the product of each combinations,
## example: for every (x,y) combo, do x*y and make a new list called z

Expected output should yield a new list with:

0.02
0.03
0.05
0.06
0.1
0.15
- - Source

Answers

answered 1 week ago Vasilis G. #1

You can do it with a simple list comprehension, you don't have to use itertools:

inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]

z = [round(elem[0]*elem[1],2) for elem in inlist]
print(z)

Output:

[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

But, if you want to use itertools, you can do it using the starmap function:

from itertools import starmap
inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]

z = list(starmap(lambda i,j: round(i*j,2), inlist))
print(z)

Output:

[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

answered 1 week ago pylang #2

You can use any iterable to make these combinations.

If you are new to Python, this answer tries to clarify some options.

Given

A reducing function mul and an iterable of data:

def mul(a, b):                                         # 1
    """Return a rounded multiple."""
    return round(a * b, 2)                             


data = [0.1, 0.2, 0.3, 0.5]                            # 2

Code

Prepare an iterable - a linear container that can be looped over. Examples:

Option 1 - An iterator

iterable = it.combinations(data, 2)

Option 2 - pandas DataFrame

df = pd.DataFrame(data, columns=["weights"])
iterable = it.combinations(df["weights"], 2)

Demo

[mul(x, y) for x, y in iterable]                      # 3
# [0.02, 0.03, 0.05, 0.06, 0.1, 0.15] 

Details

  1. This function contains the operation you want to apply.
  2. A simple iterable (e.g. list) of data. Note, it need not be nested.
  3. Use any iterable to reduce the pairs of combinations

Option 3 - pandas Operations

Alternatively, once you have data in pandas, you can stick with it:

combs = list(it.combinations(data, 2))
df = pd.DataFrame(combs, columns=["a", "b"])
df
#      a    b
# 0  0.1  0.2
# 1  0.1  0.3
# 2  0.1  0.5
# 3  0.2  0.3
# 4  0.2  0.5
# 5  0.3  0.5

df.prod(axis=1).round(2).tolist()
# [0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

I'd recommend choosing either pure Python or pandas (options 1 or 3).

comments powered by Disqus