0

I have an array which hold an integer value and item Id value in it.

I want to add two different values of two different items. For example, let's say foretold item is like this:

array1 = [[12, 1], [23, 2], [34, 3]]

and the desired output should be something like that:

[[35, 12, 1, 23, 2], [46, 12, 1, 34, 3], [57, 23, 2, 34, 3]]

For small array counts there is no problem but when the count of array exceed a hundred I encounter with huge performance problems.

Is there any method for this in Python?

My example code:

for item1 in array1:
    for item2 in array1:
        sumTwoOutput.append([item1[0] + item2[0], item1[0], item1[1], item2[0], item2[1]])

dfSumTwoOutput = pd.DataFrame(sumTwoOutput)
dfSumTwoOutput.columns = ["OutputSum", "Value1", "ItemId1", "Value2", "ItemId2"]
0

2 Answers 2

1

You can use itertools.combinations:

from itertools import combinations

array = [[12, 1], [23, 2], [34, 3]]

sumTwoOutput = []
for (num1, id1), (num2, id2) in combinations(array, 2):
    sumTwoOutput.append([num1 + num2, num1, id1, num2, id2])

print(sumTwoOutput)

This will give:

[[35, 12, 1, 23, 2], [46, 12, 1, 34, 3], [57, 23, 2, 34, 3]]

As I see from your code that you are using this with pandas, here is another way relying more on pandas:

import pandas as pd
from itertools import combinations

array = [[12, 1], [23, 2], [34, 3]]

df = pd.DataFrame((*x, *y) for x,y in combinations(array, 2))
df.columns = ["Value1", "ItemId1", "Value2", "ItemId2"]

df.insert(0, "Sum", df["Value1"] + df["Value2"])

print(df)

Gives:

   Sum  Value1  ItemId1  Value2  ItemId2
0   35      12        1      23        2
1   46      12        1      34        3
2   57      23        2      34        3
Sign up to request clarification or add additional context in comments.

Comments

0

You can use itertools package.

from itertools import combinations

array = [[12, 1], [23, 2], [34, 3]]

sumTwoOutput = []
comb = combinations(range(len(array)), 2)

for i, j in comb:
    sumTwoOutput.append([array[i][0] + array[j][0], array[i][0], array[i][1], array[j][0], array[j][1]])

print(sumTwoOutput)
# [[35, 12, 1, 23, 2], [46, 12, 1, 34, 3], [57, 23, 2, 34, 3]]

1 Comment

How is that different from my answer (except creating combinations of indexes)?

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.