如何在pandas Series中通过类get方法使用iloc式位置索引取值
解决方案
以下是两种无额外索引重置开销、支持默认值返回的实现方式:
方法1:长度校验+iloc(性能最优,最推荐)
直接先校验位置索引合法性再取值,全程不会生成额外的中间对象,性能损耗可以忽略:
# pos为要取的位置索引,越界/序列为空时返回默认空字符串 pos = 0 res = series.iloc[pos] if 0 <= pos < len(series) else ''
运行效果:
>>> series = pd.Series(data=['A', 'B'], index=[2,3]) >>> res = series.iloc[0] if 0 <= 0 < len(series) else '' >>> print(res) 'A' # 空序列场景适配 >>> empty_ser = pd.Series(dtype='object') >>> res = empty_ser.iloc[0] if 0 <= 0 < len(empty_ser) else '' >>> print(res) ''
方法2:封装通用工具函数
如果需要频繁调用该能力,可以封装成通用函数,适配任意位置、自定义默认值,用异常捕获处理边界场景:
def iloc_get(s: pd.Series, pos: int, default: str = '') -> str: try: return s.iloc[pos] except IndexError: return default
调用示例:
>>> iloc_get(series, 0) 'A' >>> iloc_get(series, 999) # 位置越界返回默认值 '' >>> iloc_get(pd.Series(), 0) # 空序列返回默认值 ''
不推荐reset_index方案的原因
reset_index(drop=True)会生成一个全新的Series对象,当原序列数据量较大时会产生不必要的内存拷贝和计算开销,对于仅需取单个值的场景完全冗余。
内容的提问来源于stack exchange,提问作者ThePyGuy
相关产品推荐
相关产品推荐

