python的iloc用法
2026/5/16 19:57:04 网站建设 项目流程

口诀

.iloc[行位置, 列位置] 只看整数下标,从左到右从 0 开始数

练习

1.调试打印前 8 行(只看前 10 列)

for i in range(8): print(df_raw.iloc[i, :10].tolist())
    写法含义
    df.iloc[r, c]单个标量
    df.iloc[r1:r2, c1:c2]连续块(切片)
    df.iloc[[r1,r2,…], [c1,c2,…]]任意行列列表
    df.iloc[:, :]全表

    3.df.iloc[0, :] 显式写“所有列”

    4.df.iloc[:, 3] Series,第4列(c3)
    5. df.iloc[::-1] 行顺序倒过来,快速把 DataFrame 上下翻转
    6. df.iloc[:, ::-1] 列顺序倒过来, 快速把 DataFrame 左右翻转
    7. df.iloc[:, 1:-1] # 去掉第 1 列和最后 1 列, 只拿数值矩阵(去掉前后文字列)
    8. 从 df 里随便拿 3 行,不放回

    rng = np.random.default_rng(42) df.iloc[rng.choice(len(df), size=3, replace=False)]

    9.用 lambda 动态选行(返回整数数组即可)
    lambda 给出的是“布尔列表”,iloc 按列表里 True 的位置拿行

    df.iloc[lambda x: x.index % 2 == 0] # 偶数行(索引号 0,2,4…)

    需要专业的网站建设服务?

    联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

    立即咨询