Python:计算数组中相同的行数(无任何导入)
例如,假设:Python:计算数组中相同的行数(无任何导入),python,arrays,list,numpy,Python,Arrays,List,Numpy,例如,假设: import numpy as np data = np.array( [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 0, 1], [0, 1, 1], [0, 0, 0]]) 我想得到一个三维数组,看起来像: result = array([[[ 2., 0.], [ 0., 2.]], [[ 0., 2.],
import numpy as np
data = np.array(
[[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 0, 1],
[0, 1, 1],
[0, 0, 0]])
我想得到一个三维数组,看起来像:
result = array([[[ 2., 0.],
[ 0., 2.]],
[[ 0., 2.],
[ 0., 0.]]])
一种方法是:
for row in data
newArray[ row[0] ][ row[1] ][ row[2] ] += 1
我想做的是:
for i in dimension1
for j in dimension2
for k in dimension3
result[i,j,k] = (data[data[data[:,0]==i, 1]==j, 2]==k).sum()
这似乎不起作用,我希望通过坚持我的实现而不是一开始提到的实现(或使用任何额外的导入,例如计数器)来实现预期的结果
谢谢。您可以执行以下操作
#Get output dimension and construct output array.
>>> dshape = tuple(data.max(axis=0)+1)
>>> dshape
(2, 2, 2)
>>> out = np.zeros(shape)
如果您有numpy 1.8+:
out.flat[np.ravel_multi_index(data.T, dshape)]+=1
其他:
Numpy 1.7之前的Numpy版本没有add.at
属性,没有该属性,顶层代码将无法工作。由于ravel\u multi\u index
可能不是考虑使用numpy数组的最快算法。实际上,这两种操作应该是等效的。您也可以使用:
>>> np.histogramdd(data, bins=(2, 2, 2))[0]
array([[[ 2., 0.],
[ 0., 2.]],
[[ 0., 2.],
[ 0., 0.]]])
问题是,
data[data[:,0]==i,1]==j,2]==k
并不是你所期望的
让我们将其分解为案例(i,j,k)==(0,0,0)
data[:,0]==0
是[True,True,False,False,True,True]
,而data[data[:,0]==0]
正确地给出了第一个数字是0
的行
现在从这些行中我们得到第二个数字是0
:data[data[:,0]==0,1]==0
,这给了我们[True,False,False,True]
。这就是问题所在。因为如果我们从数据
中获取这些索引,即数据[data[data[:,0]==0,1]==0]
我们不会得到第一个和第二个数字为0
的行,而是0th
和3rd
行:
In [51]: data[data[data[:,0]==0, 1]==0]
Out[51]: array([[0, 0, 0],
[1, 0, 1]])
如果我们现在对第三个数字为0
的行进行筛选,我们会得到错误的结果w.r.t.原始数据
这就是为什么你的方法不起作用。有关更好的方法,请参阅其他答案。不要害怕导入。正是它们让Python变得棒极了 如果问题是假设您已经有了结果矩阵
import numpy as np
data = np.array(
[[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 0, 1],
[0, 1, 1],
[0, 0, 0]]
)
result = np.zeros((2,2,2))
# range of each dim, aka allowable values for each dim
dim_ranges = zip(np.zeros(result.ndim), np.array(result.shape)-1)
dim_ranges
# Out[]:
# [(0.0, 2), (0.0, 2), (0.0, 2)]
# Multidimentional histogram will effectively "count" along each dim
sums,_ = np.histogramdd(data,bins=result.shape,range=dim_ranges)
result += sums
result
# Out[]:
# array([[[ 2., 0.],
# [ 0., 2.]],
#
# [[ 0., 2.],
# [ 0., 0.]]])
此解决方案解决任何“结果”数据阵列,无论形状如何。此外,即使“数据”数据数组的索引超出结果矩阵的界限,它也可以正常工作。我相信您使用的是numpy。是的,这是正确的,将修复它。不管怎样,有什么想法吗?我认为你的第一种方法更容易阅读,当然更快。@tobias_k我知道!我只是好奇为什么第二种方法不起作用:)请下次发布语法正确的代码
import numpy as np
data = np.array(
[[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 0, 1],
[0, 1, 1],
[0, 0, 0]]
)
result = np.zeros((2,2,2))
# range of each dim, aka allowable values for each dim
dim_ranges = zip(np.zeros(result.ndim), np.array(result.shape)-1)
dim_ranges
# Out[]:
# [(0.0, 2), (0.0, 2), (0.0, 2)]
# Multidimentional histogram will effectively "count" along each dim
sums,_ = np.histogramdd(data,bins=result.shape,range=dim_ranges)
result += sums
result
# Out[]:
# array([[[ 2., 0.],
# [ 0., 2.]],
#
# [[ 0., 2.],
# [ 0., 0.]]])