【问题标题】:Attain a tally of a column of a 2d array获得二维数组列的计数
【发布时间】:2017-02-11 06:52:19
【问题描述】:

我有一个二维数组数据。并且希望每次第 j 次迭代为 1 时都得到一个计数。 其中 i = 行和 j = 列。 如果没有 for 循环,我该如何做呢?

概念上是这样的:

for r in range(row):
    if(data[r][j] == 1)
        amount += 1

【问题讨论】:

    标签: python arrays numpy multidimensional-array scipy


    【解决方案1】:

    我对这个问题的解释是,您希望遍历行和列,并为数据中的每个条目添加 1 到 amount 为 1。这可以在不循环的情况下完成,如下所示。

    import numpy as np
    
    data = np.ones((6,8))
    amount = data[data == 1].sum()
    print amount
    

    如果不继续,你固定一栏j,只想要这一栏的金额:

    import numpy as np
    j=7
    data = np.ones((6,8))
    amount = data[:,j][data[:,j]==1].sum()
    print amount
    

    【讨论】:

    • 我想遍历特定列 j 的每一行。
    【解决方案2】:

    你可以这样做:

    import numpy as np
    a = np.array([[0, 1], [1, 1]])
    j = 1
    np.sum(a[:, j] == 1)
    

    结果会给你 2 , 而np.sum(a[:, 0] == 1) 将给出 1

    如果您在评论中提到您想在多个数组上使用条件,您可以使用np.logical_and(condition1, condition2)

    np.sum(np.logical_and(a[:, 0] == 1, b[:, 0] == 2))
    

    【讨论】:

    • 是否可以包含第二个条件?例如:np.sum(arrayB = 2 and a[:, 0] == 1)
    • @user 你可以使用 np.logical_and(a[:, 0] == 1, b[:, 0] == 2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多