所以我有一个包含两列的数据集,一个是带有产品名称的字符串变量,另一列是其他间隔值。
Affiliate_ID Average "A" Level
store X 7.0
store Y 4.3
store Z 5.6
我很好奇是否可以在python中计算和求和所有可能的成对差异,而不重复。
Sum = |7.0 - 4.3| + |4.3 - 5.6| + |7.0 - 5.6|
我不知道python执行此类操作的格式最好,但我将数据放在csv文件和excel文件中。我使用pandas将数据导入数据帧。我尝试过的一件事就是从数据框中抓取一个特定的列
df = pd.DataFrame.from_csv(infile_path + "mp_viewed_item_AGG_affiliate_item_TOP_10.csv", sep=',')
i = 0
for i in df:
x = df[i]
但这感觉不对 - 就像它无处可去(不是我知道!)
有人建议我使用一种名为itertools的东西,并为我提供了样本
sum([args[i] - args[j] for i,j in itertools.permutations(range(len(args)
但我真的不知道如何做到这一点。
如果有人能够让我对我的问题有所了解,我将非常感激。我是python的新手;我知道基础知识,编写了几个非常简单的程序,但根本不是开发人员。
答案 0 :(得分:1)
import itertools
column = [3, 1, 7, 2, 9, 4]
您可以像这样制作一组对
# You can use set() instead of list() if you want to remove duplicates
list(itertools.combinations(column,2))
输出
[(3, 1), (3, 7), (3, 2), (3, 9), (3, 4),
(1, 7), (1, 2), (1, 9), (1, 4),
(7, 2), (7, 9), (7, 4),
(2, 9), (2, 4),
(9, 4)]
然后你可以使用列表理解
来获得差异的总和sum([abs(pair[1] - pair[0]) for pair in itertools.combinations(column,2)])
输出
56
答案 1 :(得分:0)
像这样使用itertools.combinations
。
import pandas as pd
import itertools
d = {'Affiliate_ID': pd.Series(['store X', 'store Y', 'store Z']), 'Average "A" Level': pd.Series([7.0, 4.3, 5.6])}
df = pd.DataFrame(d)
print sum(abs(x - y) for x, y in itertools.combinations(df['Average "A" Level'], 2))