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

如何高效实现Pandas DataFrame按指定行索引对多行执行按位与运算

Pandas 按指定行索引批量执行按位与的高效实现

你原来的循环写法和apply写法都存在Python层运算开销大、通用性差的问题,推荐使用向量化聚合的方式实现:

推荐实现(性能最优)

基于numpy向量化运算实现,性能最好,适合大数据量场景:

import pandas as pd
import numpy as np

def bitwise_and_rows(df, indices):
    # 选中指定行后,在行维度上聚合执行按位与运算
    return df.iloc[indices].agg(np.bitwise_and.reduce, axis=0)

# 测试示例
df = pd.DataFrame([[7, 7, 7, 8], [1, 2, 4, 8], [13, 2, 13, 13], [1, 7, 14, 13]])
indices = [0,1,3]
result = bitwise_and_rows(df, indices)
print(result)

备选实现(无额外依赖)

如果不想引入numpy的接口,也可以用Python标准库实现,通用性同样不受影响,性能优于手动循环:

import pandas as pd
from functools import reduce
import operator

def bitwise_and_rows(df, indices):
    return reduce(operator.and_, (df.iloc[idx] for idx in indices))

方案优势

  • 通用适配:支持任意长度的行索引列表,不需要针对索引数量修改代码
  • 性能更高:两种实现都避免了手动编写Python层循环的额外开销,向量化实现的性能远快于手动for循环和apply遍历的实现
  • 结果格式和原有实现完全一致,不需要额外做格式转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:09:00