Biswankar Das
Biswankar Das

Reputation: 305

how to obtain index of dataframe by comparing values of a column to a string without iterrows

I have a dataframe(df) with a large number of rows :

0   A     B     C     D     E
1   ax    92    47    32    89
2   av    12    41    26    87
3   bn    54    87    98    09

string='av' I need to find the index of df with A=av it need to return 2

I tried using df.iterrows(), but there are a huge number of rows which takes a lot of time or crashes

Is it possible to do this without iterrows ?

Upvotes: 1

Views: 64

Answers (2)

Zero
Zero

Reputation: 76947

Use boolean filtering and .loc.

Three ways to access value 2 from column '0'

In [377]: df.loc[df['A'] == 'av', '0']
Out[377]:
1    2
Name: 0, dtype: int64

In [378]: df.loc[df['A'] == 'av', '0'].item()
Out[378]: 2L

In [379]: df.loc[df['A'] == 'av', '0'].iloc[0]
Out[379]: 2

Upvotes: 2

Amrith M
Amrith M

Reputation: 128

index=df.loc[df['A'] == 'av', '0'].iloc[0]

This technique is called Boolean Masking.index will have value 2 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html Refer to Pandas Documentation. Pandas is well documented !

Upvotes: 1

Related Questions