如何用矩阵中的第一个项目在R / Python中划分矩阵中的项目?

时间:2014-12-28 07:32:54

标签: python r pandas

如何将矩阵中的每个项目除以其行中的第一项。

3 个答案:

答案 0 :(得分:4)

对于未来的问题,请参阅herehere如何提出一个好问题并避免大规模的投票并获得更好的答案。

在R中,没有必要没有循环(尤其是在其中的增长对象中)

让我们说这是你的矩阵

m <- matrix(1:1344, 84, 16)

您需要做的就是获得所需的输出

m <- m/m[, 1]

将矩阵的每一行除以每行中的第一个值

为了将其保存为csv格式文件,请参阅

?write.csv

答案 1 :(得分:2)

我看到我们已经有了R的答案,但对于那些需要大熊猫的人来说:

>>> # Create a dataframe with 84 rows and 16 columns
>>> df = pd.DataFrame(np.random.rand(84, 16))
>>> 
>>> # Divide each row by the first value in the row:
>>> result = df.divide(df[0], axis='rows')
>>> 
>>> # Save to csv
>>> result.to_csv('my_file.csv')

分裂行动背后的逻辑: df [0]是数据帧的第一列。 请注意,这是因为列的名称是0,而不是因为索引是0! 如果列的名称是&#34; my_col&#34;,则该行将是 result = df.divide(df["my_col"], axis='rows')

df [0]的类型是pandas.Series。

现在,df.divide可以沿着行工作(这就是为什么我们给它参数axis =&#39; rows&#39;),这就是我们所做的: 取一个长度等于行数*的系列。然后,行中的每个值将除以系列中适当位置的值。

顺便说一句,df.divide也可以沿着列工作。但是这样做df / df[0]会更容易。

  • 注意:长度不一定是行数,但我认为它更高级且超出了范围。

答案 2 :(得分:0)

因为您的问题不是很明确,请考虑以下示例:

"""populate the matrix"""
import random
matrix = []
matrix_rows = 8
matrix_cols = 6
for i in range(matrix_rows):
    matrix.append([])
    for j in range(matrix_cols):
        matrix[i].append(random.randint(1,500))

为简单起见,我们将矩阵保持较小,所以

>>>matrix
 [[83, 425, 150, 391, 391, 452],
 [447, 32, 36, 344, 374, 315],
 [301, 442, 447, 19, 458, 63],
 [96, 282, 245, 167, 366, 356],
 [300, 19, 481, 180, 385, 17],
 [491, 266, 236, 397, 104, 477],
 [259, 365, 343, 204, 118, 449],
 [20, 192, 461, 160, 83, 391]]

现在设置一个操作矩阵的函数:

def divide_matrix(matrix):
    new_matrix = []
    counter_rows = 0
    for row in matrix:
        new_matrix.append([])
        divider = None
        counter_vals = 0
        for value in row:
            if not divider:
                new_matrix[counter_rows].append(value)
                divider = value
            else:
                new_matrix[counter_rows].append(round(value / divider,2))
            counter_vals+=1
        counter_rows+=1
    return new_matrix

并运行它:

>>>divide_matrix(matrix)
 [[83, 5.12, 1.81, 4.71, 4.71, 5.45],
 [447, 0.07, 0.08, 0.77, 0.84, 0.7],
 [301, 1.47, 1.49, 0.06, 1.52, 0.21],
 [96, 2.94, 2.55, 1.74, 3.81, 3.71],
 [300, 0.06, 1.6, 0.6, 1.28, 0.06],
 [491, 0.54, 0.48, 0.81, 0.21, 0.97],
 [259, 1.41, 1.32, 0.79, 0.46, 1.73],
 [20, 9.6, 23.05, 8.0, 4.15, 19.55]]