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

如何在Pandas中按样本名将DataFrame列值除以另一DataFrame对应值

批量对DataFrame列按样本对应因子做除法运算

需求:根据样本名称,将DataFrame rpk中指定列的所有值,对应除以DataFrame scaling_factor中相同样本对应的factor值,已知单列处理方法,需要实现批量处理所有样本。

输入数据

import pandas as pd

rpk_data = {'P1-6': [1, 2, 3, 4],
            'P1-12': [2, 4, 6, 8],
            'P1-25': [6, 12, 3, 9]
            }
rpk = pd.DataFrame.from_dict(rpk_data)

sc_f_data = {'sample': ['P1-6', 'P1-12', 'P1-25'],
             'factor': [1, 2, 3]
             }
scaling_factor = pd.DataFrame.from_dict(sc_f_data)

# 单列处理示例
divided_value = rpk.loc[0, 'P1-6'] / scaling_factor.loc[0, 'factor'] # 结果为1

期望输出

P1-6  P1-12  P1-25
0     1      1      2
1     2      2      4
2     3      3      1
3     4      4      3

批量处理解决方案

利用Pandas的广播特性,两步即可完成批量计算:

  1. 将scaling_factor转换为以sample为索引的Series,让索引与rpk的列名一一对应;
  2. 使用div()方法指定按列(axis='columns')进行除法运算,Pandas会自动匹配列名与索引,完成每列所有元素的批量除法。

代码实现:

# 转换为索引匹配的Series
factor_series = scaling_factor.set_index('sample')['factor']
# 批量除法计算
result = rpk.div(factor_series, axis='columns')

# 查看结果
print(result)

该方法效率远高于循环或apply,适合处理大规模数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:03:15