比较单列中的值

时间:2018-01-22 09:11:44

标签: python pandas

我有一个专栏

df = pd.DataFrame({'Name': ['Harry', 'John', 'Peter', 'Stan', 'Petra'], 'Score': [10, 9, 5, 7, 8]})

我可以使用itertools来获取矩阵

for a, b in itertools.combinations(df['Score'], 2):
    print (a, b)

返回矩阵的最佳方法是将每个值与x和y索引进行比较。例如:

      Harry   John   Peter   Stan   Petra
Harry   -       1      5       3       2
John    -1      -      4       2       1
etc....

1 个答案:

答案 0 :(得分:1)

您可以将np.subtract.outerDataFrame构造函数一起使用:

df = pd.DataFrame(np.subtract.outer(df['Score'], df['Score']),
                  index=df['Name'], 
                  columns=df['Name'])

broadcasting

a = df['Score'].values
df = pd.DataFrame(a[:, None] - a, columns = df['Name'], index=df['Name'])

print (df)
Name   Harry  John  Peter  Stan  Petra
Name                                  
Harry      0     1      5     3      2
John      -1     0      4     2      1
Peter     -5    -4      0    -2     -3
Stan      -3    -2      2     0     -1
Petra     -2    -1      3     1      0