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

如何在Pandas DataFrame中提取列的部分数据?以数独3×3区块为例

用Pandas DataFrame提取数独3×3区块

要从数独的DataFrame中提取连续的3×3区块,关键是用iloc的连续范围切片(而非离散列/行索引),因为数独的区块都是连续的3行3列。以下是具体实现:

提取单个3×3区块

iloc支持行范围:列范围的切片语法,切片是左闭右开,所以0:3会选取索引0、1、2的行/列,正好覆盖3个连续位置。

示例代码

import pandas as pd
Sudoku_Board = [
    [0, 2, 5, 6, 3, 1, 8, 4, 7],
    [6, 1, 8, 5, 0, 4, 2, 9, 3],
    [3, 7, 4, 9, 8, 2, 5, 0, 1],
    [7, 4, 9, 8, 2, 6, 0, 3, 5],
    [8, 5, 2, 4, 1, 0, 9, 7, 6],
    [1, 6, 0, 7, 9, 5, 4, 8, 2],
    [2, 0, 7, 3, 5, 9, 6, 1, 4],
    [4, 9, 1, 0, 6, 7, 3, 5, 8],
    [5, 3, 6, 1, 4, 8, 7, 2, 0]
]
df = pd.DataFrame(Sudoku_Board)

# 提取左上角区块(行0-2,列0-2)
top_left = df.iloc[0:3, 0:3]
print("左上角3×3区块:")
print(top_left)

# 提取中间区块(行3-5,列3-5)
middle = df.iloc[3:6, 3:6]
print("\n中间3×3区块:")
print(middle)

# 提取右下角区块(行6-9,列6-9)
bottom_right = df.iloc[6:9, 6:9]
print("\n右下角3×3区块:")
print(bottom_right)

遍历所有9个3×3区块

如果需要一次性获取所有区块,可以用循环遍历行和列的起始索引(每次步进3):

# 遍历所有9个区块
for row_start in range(0, 9, 3):
    for col_start in range(0, 9, 3):
        block = df.iloc[row_start:row_start+3, col_start:col_start+3]
        print(f"\n区块起始位置({row_start}, {col_start}):")
        print(block)

为什么之前的方法不对?

你之前用df.iloc[:,[1,3,4]]是选取离散的列(索引1、3、4),而非连续的列范围。要提取连续的列,需要用起始索引:结束索引的格式,比如3:6代表列3、4、5。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:00:20