Python - 两个变量之和取决于第三个变量的矩阵

Python - Matrix with the sum of two variable depending on a third

我正在尝试分析两个变量在阈值函数中的演变。 我从这样的数据框开始:

list1 = [[0,6,3], [100,6,1], [200,4,1], [300,3,0], [400,3,0], [500,0,0]]
cols = ['threshold', 'var_1', 'var_2']
raw = pd.DataFrame(list1, columns=cols)
raw.head()


threshold   var_1   var_2
     0        6       3
   100        6       1
   200        4       1
   300        3       0
   400        3       0 

目标是像这样表示取决于阈值的两个变量的总和,以在热图中使用:

            500 3   1   1   0   0   0
            400 5   3   3   2   2   2
    var_1   300 6   4   4   3   3   3
            200 7   5   5   4   4   4
            100 9   7   7   6   6   6
              0 9   7   7   6   6   6
                0   100 200 300 400 500
                          var_2             

我试过 corrstab 和 pivot_table 但我没有得到这个结果。

在搜索 Pandas 文档后,我也找不到提供您显示的结果的任何内置函数。有一种自制的解决方案可能适合您;它依赖于使用 Python 的 itertools.product 形成的迭代器来表示两个变量的所有组合。

这个解决方案没有优化,因为对于更大规模的数据,这个迭代器会比 Numpy 和 Pandas 的内置迭代器慢。不过,对于您这种大小的矩阵,它应该还是相当快的。

list1 = [[0,6,3], [100,6,1], [200,4,1], [300,3,0], [400,3,0], [500,0,0]]
cols = ['threshold', 'var_1', 'var_2']
raw = pd.DataFrame(list1, columns=cols)
nrows = len(raw.index)
combos = itertools.product(range(nrows), range(nrows))
heatmap = np.zeros((nrows + 1, nrows + 1))
heatmap[:-1, 0] = np.flip(raw['threshold'])
heatmap[-1, 1:] = raw['threshold']
for combo in combos:
  heatmap[heatmap.shape[0] - combo[0] - 2, combo[1] + 1] =\
    raw['var_1'][combo[0]] + raw['var_2'][combo[1]]
print(heatmap)
[[500.   3.   1.   1.   0.   0.   0.]
 [400.   6.   4.   4.   3.   3.   3.]
 [300.   6.   4.   4.   3.   3.   3.]
 [200.   7.   5.   5.   4.   4.   4.]
 [100.   9.   7.   7.   6.   6.   6.]
 [  0.   9.   7.   7.   6.   6.   6.]
 [  0.   0. 100. 200. 300. 400. 500.]]

这是我想到的最好的。似乎它也很有效 经过模式研究,我来到了这个解决方案

代码:

import pandas as pd
import numpy as np

list1 = [[0,6,3], [100,6,1], [200,4,1], [300,3,0], [400,3,0], [500,0,0]]
cols = ['threshold', 'var_1', 'var_2']
raw = pd.DataFrame(list1, columns=cols)

for i, col_name in enumerate(raw['threshold'].values):
    raw[col_name] = raw.iloc[i,2] + raw.iloc[:,1]

print(raw)

输出:

   threshold  var_1  var_2  0  100  200  300  400  500
0          0      6      3  9    7    7    6    6    6
1        100      6      1  9    7    7    6    6    6
2        200      4      1  7    5    5    4    4    4
3        300      3      0  6    4    4    3    3    3
4        400      3      0  6    4    4    3    3    3
5        500      0      0  3    1    1    0    0    0