Python:在每列中将单元格中的值除以max

Bla*_*ack 5 python numpy

这是一种有效或正确的方法,可以将每列中的每个单元格除以表中该列中的最大值吗?是否有更好的实施(如果这是正确的)?注意:所有值> = 0

new_data = [];
for row in np.transpose(data)[1::]: #from 1 till end
    for elements in row:
        if sum(elements) != 0:
            new_data.append(elements/max(row));
        else:
            new_data.append(0);
new_data = np.transpose(new_data);
Run Code Online (Sandbox Code Playgroud)

现在:

id col1 col2 col3 col4
A   2    1    4    0
B   3    8    2    0
C   2    3    0    0
D   5    5    3    0
E   6    3    3    0
Run Code Online (Sandbox Code Playgroud)

需要:

id col1 col2 col3 col4
A  1/3  1/8  1     0  
B  1/2  1    1/2   0
C  1/3  3/8  0     0
D  5/6  5/8  3/4   0
E  1    3/8  3/4   0
Run Code Online (Sandbox Code Playgroud)

CT *_*Zhu 5

你怎么处理0?喜欢最后一栏吗?nan理论上应该是这样。(sum(elements) != 0,如果它是 -2 -1 0 1 2 呢?那应该是 -1 -0.5 0 0.5 1,对吧?)

In [138]:

A*1./np.max(A, axis=0)
Out[138]:
array([[ 0.33333333,  0.125     ,  1.        ,         nan],
       [ 0.5       ,  1.        ,  0.5       ,         nan],
       [ 0.33333333,  0.375     ,  0.        ,         nan],
       [ 0.83333333,  0.625     ,  0.75      ,         nan],
       [ 1.        ,  0.375     ,  0.75      ,         nan]])
Run Code Online (Sandbox Code Playgroud)

我们可以保留最后一列。

In [141]:

np.where(np.max(A, axis=0)==0, A, A*1./np.max(A, axis=0))
Out[141]:
array([[ 0.33333333,  0.125     ,  1.        ,  0.        ],
       [ 0.5       ,  1.        ,  0.5       ,  0.        ],
       [ 0.33333333,  0.375     ,  0.        ,  0.        ],
       [ 0.83333333,  0.625     ,  0.75      ,  0.        ],
       [ 1.        ,  0.375     ,  0.75      ,  0.        ]])
Run Code Online (Sandbox Code Playgroud)

使用循环执行此操作的正确方法是:

for row in A.T:
    if max(row)>0:
        new_data.append([item*1./max(row) for item in row])
    else:
        new_data.append(row)
Run Code Online (Sandbox Code Playgroud)