How to find the index of an array within an array

后端 未结 3 1767
一生所求
一生所求 2021-01-03 01:18

I have created an array in the way shown below; which represents 3 pairs of co-ordinates. My issue is I don\'t seem to be able to find the index of a particular pair of co-o

3条回答
  •  孤独总比滥情好
    2021-01-03 01:54

    Numpy arrays don't an index function, for a number of reasons. However, I think you're wanting something different.

    For example, the code you mentioned:

    v = []
    for A in R:
        v.append(R.index(A))
    

    Would just be (assuming R has unique rows, for the moment):

    v = range(len(R))
    

    However, I think you might be wanting the built-in function enumerate. E.g.

    for i, row in enumerate(R):
        # Presumably you're doing something else with "row"...
        v.append(i)
    

    For example, let's say we wanted to know the indies where the sum of each row was greater than 1.

    One way to do this would be:

    v = []
    for i, row in enumerate(R)
        if sum(row) > 1:
            v.append(i)
    

    However, numpy also provides other ways of doing this, if you're working with numpy arrays. For example, the equivalent to the code above would be:

    v, = np.where(R.sum(axis=1) > 1)
    

    If you're just getting started with python, focus on understanding the first example before worry too much about the best way to do things with numpy. Just be aware that numpy arrays behave very differently than lists.

提交回复
热议问题