[英]Addition of Two Different Columns of Same Array
I have an array which hold an integer value and item Id value in it.我有一个数组,其中包含一个整数值和项目 Id 值。
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?在 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"]
You can use itertools.combinations
:您可以使用
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
:正如我从您的代码中看到的,您将它与
pandas
一起使用,这是另一种更依赖于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
You can use itertools package.您可以使用 itertools 包。
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.