Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 添加同一数组的两个不同列_Python - Fatal编程技术网

Python 添加同一数组的两个不同列

Python 添加同一数组的两个不同列,python,Python,我有一个数组,其中包含一个整数值和item Id值 我想添加两个不同项目的两个不同值。例如,假设预测项如下所示: array1 = [[12, 1], [23, 2], [34, 3]] 期望的输出应该是这样的: [[35, 12, 1, 23, 2], [46, 12, 1, 34, 3], [57, 23, 2, 34, 3]] 对于小数组计数没有问题,但是当数组计数超过100时,我会遇到巨大的性能问题 Python中是否有用于此的方法 我的示例代码: for item1 in arra

我有一个数组,其中包含一个整数值和item Id值

我想添加两个不同项目的两个不同值。例如,假设预测项如下所示:

array1 = [[12, 1], [23, 2], [34, 3]]
期望的输出应该是这样的:

[[35, 12, 1, 23, 2], [46, 12, 1, 34, 3], [57, 23, 2, 34, 3]]
对于小数组计数没有问题,但是当数组计数超过100时,我会遇到巨大的性能问题

Python中是否有用于此的方法

我的示例代码:

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"]
您可以使用:

来自itertools导入组合的

数组=[[12,1],[23,2],[34,3]]
sumTwoOutput=[]
对于组合(数组,2)中的(num1,id1),(num2,id2):
追加([num1+num2,num1,id1,num2,id2])
打印(输出)
这将提供:

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

正如我从您的代码中看到的,您正在将其与
pandas
一起使用,这里有另一种更依赖
pandas
的方法:

将熊猫作为pd导入
从itertools导入组合
数组=[[12,1],[23,2],[34,3]]
df=pd.DataFrame((*x,*y)表示x,y的组合(数组,2))
df.columns=[“Value1”、“ItemId1”、“Value2”、“ItemId2”]
df.插入(0,“总和”,df[“值1”]+df[“值2”])
打印(df)
给出:

   Sum  Value1  ItemId1  Value2  ItemId2
0   35      12        1      23        2
1   46      12        1      34        3
2   57      23        2      34        3

您可以使用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]]

这与我的答案有什么不同(除了创建索引组合)?