Dan_Lee
Dan_Lee

Reputation: 97

Python list index

I have the following table

    userid  eventid urlclick
0   A   EID-1   [0, 2, 2, 4, 0]
1   A   EID-2   [1, 0, 2, 5, 1]

And my goal is to get the index of the particular value for urlclick column to have the result as


userid  eventid urlclick    urlclick_ind
0   A   EID-1   [0, 2, 2, 4, 0] [0, 4]
1   A   EID-2   [1, 0, 2, 5, 1] [1]

I achieved it using the following code. But is there a better way to do it?

new_ind = []
for row in time1.urlclick:
    ind = 0
    indlst = []
    for element in row:
        if element == 0:
            indlst.append(ind)
        ind += 1
    
    new_ind.append(indlst)

time1['urlclick_ind'] = new_ind        

Upvotes: 0

Views: 86

Answers (2)

R. Marolahy
R. Marolahy

Reputation: 1596

You can also try np.where:

np.where(np.array([0, 2, 2, 4, 0]) == 0)[0].tolist()
np.where(np.array([1, 0, 2, 5, 1]) == 0)[0].tolist()

output:

[0, 4]
[1]

Upvotes: 0

Daweo
Daweo

Reputation: 36735

You might use enumerate and list comprehension for this task as follows

def find_zeros(row):
    return [inx for inx,i in enumerate(row) if i==0]

print(find_zeros([0, 2, 2, 4, 0]))
print(find_zeros([1, 0, 2, 5, 1]))

output

[0, 4]
[1]

Upvotes: 2

Related Questions