如何在numpy中添加计算/计算列?
作者:互联网
假设我有一个numpy数组:
1 10
2 20
3 0
4 30
我想添加第三列,其中每一行是该行中前两列的总和(或一些任意计算):
1 10 11
2 20 22
3 0 3
4 30 34
我怎么做?
解决方法:
import numpy
my_arr = numpy.array([[1, 10],
[2, 20],
[3, 0],
[4, 30]])
column0 = my_arr[:,0:1] # Use 0:1 as a dummy slice to maintain a 2d array
column1 = my_arr[:,1:2] # Use 1:2 as a dummy slice to maintain a 2d array
new_column = column0 + column1
my_arr = numpy.hstack((my_arr, new_column))
标签:calculated-columns,python,arrays,numpy 来源: https://codeday.me/bug/20190723/1513081.html