5

How do I print/return the index of a particular value?

movies_per_year = pd.DataFrame(movies_per_year)
movies_per_year.columns = ["count"]
print(movies_per_year)

        count
year       
1891      1
1893      1
1894      2
1895      2
1896      2
1898      5

Here, my index is the year. I want to return all the indexes where count is 1. Furthermore movies_per_year.max() returns 5. So, it should return 1898.

Yash Ghorpade
  • 607
  • 1
  • 7
  • 16

1 Answers1

9

np.where() - returns positional indices of the elements that satisfy the given condition:

In [31]: np.where(df['count'] == 1)[0]
Out[31]: array([0, 1], dtype=int64)

or

In [35]: np.nonzero(df['count'] == 1)
Out[35]: (array([0, 1], dtype=int64),)

if you need real index values (labels) instead of their positions:

In [40]: df.index[df['count'] == 1]
Out[40]: Int64Index([1891, 1893], dtype='int64', name='year')

to find an index of a maximum element:

In [32]: df['count'].idxmax()
Out[32]: 1898
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419