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

Python中Feather格式数据块读写及特定块查询方法咨询

读取Feather分块文件的特定数据块方法

作为Python和数据库领域新手,你可以通过两种实用方式读取Feather文件里的特定数据块,以下是具体操作:

方法1:通过行号范围直接读取

write_feather的chunksize是按行划分数据块的,你可以根据目标块编号计算对应行的起始位置,再用read_feather的参数精准读取:

示例代码

import pyarrow.feather as feather

# 写入时指定的chunksize值
chunksize = 2000
# 要读取第2个块(索引从0开始,对应第4000-5999行)
target_chunk = 2

# 计算起始行位置
start_row = target_chunk * chunksize
# 读取指定范围的块
chunk_df = feather.read_feather(
    'large_data.feather',
    skip_rows=start_row,
    n_rows=chunksize
)

如果不清楚总行数,可以快速获取来确认总块数:

# 仅读取空列获取总行数,避免加载整个数据集
total_rows = feather.read_feather('large_data.feather', columns=[]).shape[0]
total_chunks = total_rows // chunksize + (1 if total_rows % chunksize != 0 else 0)
print(f"总共有{total_chunks}个数据块")

方法2:用PyArrow Dataset API(更灵活)

PyArrow的Dataset模块支持按需读取数据块,还能直接在块内做过滤查询,适合处理超大型数据集:

示例代码

import pyarrow.dataset as ds

# 创建Dataset对象关联Feather文件
dataset = ds.dataset('large_data.feather', format='feather')

# 读取第2个数据块(Dataset的batches对应写入时的chunks)
batches = list(dataset.to_batches())
chunk_df = batches[2].to_pandas()

# 进阶:带条件过滤读取块内数据
# 比如只读取第2块中col1大于4500的行
filter_condition = ds.field('col1') > 4500
filtered_batch = next(dataset.to_batches(filter=filter_condition))
filtered_df = filtered_batch.to_pandas()

注意事项

  • 读取时的chunksize必须和写入时一致,否则会读错块范围
  • 超大型数据集优先用Dataset API,它无需加载整个文件到内存,效率更高
  • Feather的分块是行级划分,无法直接按列分块读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:35:18