Lostsoul
Lostsoul

Reputation: 26037

In Pandas can I get the index number of the first match?

Given:

df['col1']

0                company_id
1     current_value scope 1
2     current_value scope 2
3     current_value scope 3
4                      Name
5                    Intuit
6                       NaN
7                       NaN
8              PROJECT DATA
9                      Name
10                      NaN
11                      NaN
12                      NaN
13                      NaN
14                      NaN
Name: Url, dtype: object

Can I figure out what the index of the first instance of "name" is, in this case it would be 4? I tried:

df[['column1'=="Name"]].index[0]

but I'm getting

ValueError: Item wrong length 1 instead of 15.

Upvotes: 0

Views: 49

Answers (1)

user7864386
user7864386

Reputation:

You get that error because ['col1'=='Name'] returns [False] and since the length of df is 15, you can't filter it with a list of length 1 (the length of the boolean mask has to be the same as the length of the DataFrame/Series).

You could create a boolean mask by:

msk = df['col1'].eq('Name')

Then you could use the idxmax method:

out = msk.idxmax()

Alternatively, you could use msk to filter df or its index:

idx = df.index[msk]

This returns an IntIndex object of length 2 (since there are 2 "Name"s in "col1"). Then to get the first, you can index it:

out = idx[0]

Upvotes: 1

Related Questions