简体   繁体   English

如何从当前列中减去前一列,并使用numpy使用该值在数组中创建新维?

[英]How to subtract the previous rows column from current column and create a new dimension in the array with this value using numpy?

What I want to do is take my current array and subtract the previous rows column value from the current rows column value. 我想做的是获取当前数组,并从当前行列值中减去前几行的值。 I also want to take the result and add it to the array as a new dimension. 我也想获取结果并将其作为新维度添加到数组中。

Example Array: 示例数组:

[[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]]

Lets say I want to do this with the 4th column so I want the output to be an array that looks like this: 可以说我想在第4列中执行此操作,因此我希望输出是一个看起来像这样的数组:

[[1,2,4,7,9,15,0], [3, 4,3,5,10,2,-2], [5,6,56,7,20,1,2]]

Thanks 谢谢

You can do this using a combination of np.diff , and concatenate options, like so: 您可以结合使用np.diffconcatenate选项来执行此操作,如下所示:

import numpy as np
myarray = np.array([[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]])
#your differences appears to be wraparound, so we repeat the last row at the top:
myarray_wrap = np.vstack((myarray[-1],myarray))
#this gets the diffs for all columns:
column_diffs = np.diff(myarray_wrap, axis=0)
#now we add in only the the column_diff that we want, at the end:
print np.hstack((myarray, column_diffs[:,3].reshape(-1,1)))
#Output:
[[ 1  2  4  7  9 15  0]
 [ 3  4  3  5 10  2 -2]
 [ 5  6 56  7 20  1  2]]

This Python code should solve your problem. 此Python代码应该可以解决您的问题。

previous = None
for row in rows:
 current = row[4]
 row.append( 0 if previous == None else current - previous )
 previous = current

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一列的值除以前一行的列(而不是同一列),并将结果作为新维度添加到numpy数组中? - How to divide one columns value by a previous rows column(not the same column) and add the result as a new dimension to a numpy array? 如何从 pandas dataframe 中的当前行中减去前一行以创建一个新列,以每个名称重新启动进程? - How to subtract previous row from current row in a pandas dataframe to create a new column restarting the process with each name? Pandas:如何使用现有列和新创建列中的先前行创建新列? - Pandas : How can I create new column using previous rows from existing column and newly created column? 从Pandas列中的当前行值中减去前一行的值 - Subtract previous row value from the current row value in a Pandas column 当当前行和先前行中的名称(A 列中)匹配时,如何创建具有先前值(B 列中)的列? - How do I create a column with a previous value (in column B) when the names (in column A) in current and previous rows matches? 减去上一行中的值以按主题创建新列 - Subtract with value in previous row to create a new column by subject 创建一个前N行的新列作为数组 - Create a new Column of previous N rows as an Array 使用前面的行创建一个新列,pandas - Create a new column using the previous rows , pandas 按列减去Numpy数组 - Subtract Numpy Array by Column 如何组合多个 if 条件以创建新列并从前一行添加或减去 - How can I combine multiple if conditions to create a new column and add or subtract from the previous row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM