Pandas筛选指定国家员工遇索引越界,修改后仍无数据求助
筛选DataFrame中指定国家员工时的索引错误及无结果问题
原始代码
import pandas as pd import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup your_origin_country = 'China' employee_data = df employee_data selected_employee = employee_data[employee_data['origin_country'] == your_origin_country].iloc[0]
数据源(DataFrame)
| first_name | last_name | gender | position | salary | origin_country | |
|---|---|---|---|---|---|---|
| Tawnya | Witheford | twitheford0@seattletimes.com | Female | Technical Architect | 58286 | Russia |
| Anna | Witheford | twitheford0@seattletimes.com | Female | Technical Architect | 58286 | Mexico |
| Annie | Witheford | twitheford0@seattletimes.com | Female | Technical Architect | 58286 | China |
运行报错
IndexError Traceback (most recent call last) in <cell line: 14>() 12 # Assuming you have a DataFrame named 'employee_data' with columns like 'origin_country', 'employee_id' 13 # Replace 'employee_data' with your actual DataFrame ---> 14 selected_employee = employee_data[employee_data['origin_country'] == your_origin_country].iloc[0,:] 4 frames /usr/local/lib/python3.10/dist-packages/pandas/core/indexing.py in _validate_integer(self, key, axis) 1555 len_axis = len(self.obj._get_axis(axis)) 1556 if key >= len_axis or key < -len_axis: -> 1557 raise IndexError("single positional indexer is out-of-bounds") 1558 1559 # ------------------------------------------------------------------- IndexError: single positional indexer is out-of-bounds
修改后的代码
import pandas as pd import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup # Step 1: Select an Employee # Replace 'your_origin_country' with the desired country your_origin_country = 'Canada' employee_data = df employee_data # Assuming you have a DataFrame named 'employee_data' with columns like 'origin_country', 'employee_id' # Replace 'employee_data' with your actual DataFrame selected_employee = employee_data[employee_data['origin_country'] == your_origin_country].reset_index() selected_employee.head(1)
问题说明
原本希望筛选出国籍为'China'的员工,运行原始代码时触发索引越界错误。修改代码后,得到的结果是空表头且无数据,需要解决该问题。
内容的提问来源于stack exchange,提问作者anna
相关产品推荐
相关产品推荐

