You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字符串设置Pandas中的iloc索引?

用字符串索引实现pandas iloc的列选择

要实现用字符串格式的索引调用iloc,你可以写一个简单的解析函数,把字符串转换成iloc能识别的索引格式。下面是完整的解决方案:

解析函数与完整代码

import pandas as pd
import numpy as np

def parse_col_index(s):
    # 分割字符串并去除多余空格
    parts = [p.strip() for p in s.split(',')]
    index_parts = []
    for part in parts:
        if ':' in part:
            # 处理切片格式,比如"1:4"、":3"、"2:"
            start_end = part.split(':')
            start = int(start_end[0]) if start_end[0] else None
            end = int(start_end[1]) if start_end[1] else None
            index_parts.append(slice(start, end))
        else:
            # 处理单个列索引
            index_parts.append(int(part))
    # 合并切片和单个索引为iloc可识别的数组
    return np.r_[tuple(index_parts)]

# 测试代码
df = pd.DataFrame([[1,2,3,4,5],[4,5,6,4,5],[7,8,9,4,5],[10,11,12,4,5]])
df.columns = ["money","job","fruits","animals","height"]
tests = ["1:2","2:3", "1:4",  "1:3, 4"]

for idx_str in tests:
    print(f"索引字符串: {idx_str}")
    print(df.iloc[:, parse_col_index(idx_str)])
    print("-"*30)

函数工作原理

  • 分割处理:先把输入的索引字符串按逗号分割,同时去除每个部分的空格,兼容"1:3, 4"这种带空格的写法。
  • 切片解析:如果某个部分包含冒号,就分割成起始和结束位置,空值(比如:3或2:)会被转换成None,对应slice对象的默认起始/结束规则(从第0列开始或到最后一列结束)。
  • 单索引解析:如果是单个数字字符串,直接转换成整数索引。
  • 合并索引:用np.r_把切片和单个索引合并成连续的索引数组,iloc可以直接使用这个数组选择列。

输出结果示例

运行代码后,每个测试用例都会输出对应的列数据,比如"1:3, 4"会选择第1、2、4列(对应job、fruits、height列)。

内容的提问来源于stack exchange,提问作者x H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:20:28