在R/Python中,如何将矩阵中的一项除以其行中的第一项? 我如何将矩阵中的每一个项目按其行中的第一个项目来划分?
,因为你的问题不是很清楚,请考虑下面的例子:在R/Python中,如何将矩阵中的一项除以其行中的第一项? 我如何将矩阵中的每一个项目按其行中的第一个项目来划分?,python,r,pandas,Python,R,Pandas,,因为你的问题不是很清楚,请考虑下面的例子: """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)) 为了简单起见,我们将
"""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]]
对于未来的问题,请参阅以及如何提出一个好的问题,避免大量的反对票,并获得更好的答案 在R中,不需要任何循环(尤其是在循环中不断增长的对象) 假设这是你的矩阵
m <- matrix(1:1344, 84, 16)
m我看到我们已经有了关于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!
如果列的名称是“my_col”,那么该行将是
result=df.divide(df[“my_col”],axis='rows')
df[0]的类型是pandas.Series
现在,df.divide可以沿行工作(这就是为什么我们给它参数axis='rows'),这就是我们所做的:
取一个长度等于行数*的序列。然后,行中的每个值将除以序列中适当位置的值
顺便说一下,df.divide也可以沿列工作。但是这样做更容易df/df[0]
- 注意:长度不必是行数,但我认为这更高级,超出了范围
我会记住这一点(不要使用不必要的循环)以备将来使用。:)@Pj_uu很抱歉对你太苛刻了,尽管我强烈建议你阅读《那很好,大卫》,这是我学习的好方法。你的评论对我来说真的很有价值。:-)不知道数据帧,但是如果它是NumPy数组,那么arr/arr[:,0][:,None]
应该可以。
>>> # 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')