我有这样的文本文件:
0 0 0 1 2
0 0 1 3 1
0 1 0 4 1
0 1 1 2 3
1 0 0 5 3
1 0 1 1 3
1 1 0 4 5
1 1 1 6 1
让我们将这些列标记为:
s1 a s2 r t
我还有另一个带有伪值的数组(为了简单起见)
>>> V = np.array([10.,20.])
我想对这些性能良好的数字进行一定的计算。我想要执行的计算是:对于每个s1
,我想要每个a
的最大和t*(r+V[s1])
。
比如说,
所以最大值是50,这是我想要作为s1=0
的输出得到的值。
另外,请注意,在上述计算中,10是V[s1]
如果文件中没有最后三行,那么对于s1=1
,我只返回3*(5+20)=75
,其中20
是V[s1]
。所以最终的愿望结果是[50,75]
因此,我认为numpy最好按如下方式加载它(为了简单起见,只考虑s1=0的值)
>>> c1=[[ [ [0,1,2],[1,3,1] ],[ [0,4,1],[1,2,3] ] ]]
>>> import numpy as np
>>> c1arr = np.array(c1)
>>> c1arr #when I actually load from file, its not loading as this (check Q2 below)
array([[[[0, 1, 2],
[1, 3, 1]],
[[0, 4, 1],
[1, 2, 3]]]])
>>> np.sum(c1arr[0,0][:,2]*(c1arr[0,0][:,1]+V)) #sum over t*(r+V)
45.0
Q1.我猜不出,我如何修改上面的内容以获得numpy数组[45.0,80.0]
,这样我就可以通过它获得numpy.max
Q2.当我实际加载文件时,我无法像上面评论中所述的那样将其作为c1arr
加载。相反,我得到的信息如下:
>>> type(a) #a is populated by parsing file
<class 'list'>
>>> print(a)
[[[[0, -0.9, 0.3], [1, 0.9, 0.6]], [[0, -0.2, 0.6], [1, 0.7, 0.3]]], [[[1, 0.2, 1.0]], [[0, -0.8, 1.0]]]]
>>> np.array(a) #note that this is not same as c1arr above
<string>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
array([[list([[0, -0.9, 0.3], [1, 0.9, 0.6]]),
list([[0, -0.2, 0.6], [1, 0.7, 0.3]])],
[list([[1, 0.2, 1.0]]),
list([[0, -0.8, 1.0]])]], dtype=object)
我怎样才能解决这个问题
第三季度。是否有更好的总体方法,比如以不同的方式布置numpy阵列?(考虑到我不允许使用熊猫,但只能使用numpy)
在我看来,最直观和可维护的方法 是使用熊猫,您可以在其中为列指定名称。 另一个重要因素是,仅在熊猫中分组就容易得多
由于您的输入样本只包含整数,因此我定义了V 也作为整数数组:
我阅读了您的输入文件,如下所示:
(打印以查看已读内容)
然后,为了获得s1和a的每个组合的结果, 您可以运行:
请注意,在引用命名列时,此代码很容易阅读
结果是:
每个结果都是整数,因为V也是一个 int类型。但是如果你像在你的帖子中一样定义它(一个 数组float),结果也将是float类型 (你的选择)
如果要获得每个s1的最大结果,请运行:
这一次的结果是:
Numpy版本
如果你真的被限制为Numpy,还有一个解决方案, 虽然更难阅读和更新
读取输入文件:
最初我尝试了int类型,就像在pandasonic解决方案中一样, 但您的一条评论指出,最右边的两列是float。 因此,由于Numpy数组必须是单一类型,因此整个 数组必须是浮点类型
运行以下代码:
结果(aNumpy数组)为:
左列包含s1值和右-最大值 将第二级分组中的值分组
具有结构化数组的Numpy版本
实际上,您还可以使用Numpy结构化数组。 那么代码至少更具可读性,因为您引用了列名, 而不是列号
读取传递带有列名和类型的dtype的数组:
然后运行:
相关问题 更多 >
编程相关推荐