Home>

The following error message occurred while implementing a function that extracts data that meets certain conditions from a csv file using pandas and displays the value of the extracted data.
Since the value of n is larger than the number of extracted data, I think it is an error that occurs, but I would like to know the solution.

IndexError: single positional indexer is out-of-bounds
Corresponding source code
import pandas as pd
import sys
n = 0
shain_data = pd.read_csv ("/content/shain-list.csv",
                    encoding = "utf-8",
                    names = ('code','shimei','furigana','section','flag','nyusha_date','taisha_date'))
search_name = input ("Enter the name I want to search for in Kanji.") #Conditions I want to search
result = shain_data [shain_data ['shimei']. str.contains (search_name)] # Extract by condition
result_shimei = result ['shimei']
for i in result:
  result_shimei = result ['shimei']
  result_shimei_only = result_shimei.iloc [n]
  n = n + 1
  print (result_shimei_only)
What I tried

I tried to count the number of extracted data and turn the for statement, but I couldn't do it.

The value of result_shimei.

1 Chiharu Yamamura
5 Terumi Takayama
7 Misa Oyamada
35 Shinkichi Koyama
Name: shimei, dtype: object

Supplementary information (FW/tool version, etc.)

IndexError Traceback (most recent call last)
in()
2 for i in result:
3 result_shimei = result ['shimei']
---->4 result_shimei_only = result_shimei.iloc [n]
5 n = n + 1
6 print (result_shimei_only)

2 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _validate_integer (self, key, axis)
1435 len_axis = len (self.obj._get_axis (axis))
1436 if key>= len_axis or key<-len_axis:
->1437 raise IndexError ("single positional indexer is out-of-bounds")
1438
1439 # ------------------------------------------------ -------------------

IndexError: single positional indexer is out-of-bounds

  • Answer # 1

    The following error message occurred while implementing a function that extracts data that meets certain conditions from a csv file using pandas and displays the value of the extracted data.

    for index, row in result.iterrows ():
        result_shimei = row ['shimei']
        print (result_shimei)

    It's pretty omission, but isn't this what you expected?

    For iterrows (), see here (https://note.nkmk.me/python-pandas-dataframe-for-iteration/).