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

如何在Python中借助另一个DataFrame循环调用列以复用代码?

实现方法

你可以通过遍历df1的每一行,提取对应的列名后执行计算逻辑,下面提供几种实用的实现方式:

方式一:逐行遍历并合并所有结果

适合需要把所有计算结果整合到同一个DataFrame的场景:

import pandas as pd

# 模拟你的示例数据
df = pd.DataFrame({
    'A1': [1,2,3,4],
    'A2': [2,3,4,5],
    'A3': [6,7,8,9],
    'B1': [10,11,12,13],
    'B2': [14,15,16,17],
    'B3': [18,19,20,21],
    'C1': [20,21,22,23],
    'C2': [24,25,26,27],
    'C3': [28,29,30,31]
})

df1 = pd.DataFrame({
    'A': ['A1', 'A2', 'A3'],
    'B': ['B1', 'B2', 'B3'],
    'C': ['C1', 'C2', 'C3']
})

# 初始化空DataFrame存最终结果
result_df = pd.DataFrame()

# 遍历df1每一行
for _, row in df1.iterrows():
    # 提取当前行的列名映射
    new_col = row['A']
    num_col = row['B']
    den_col = row['C']
    
    # 计算并添加到结果DataFrame
    result_df[new_col] = (df[num_col] / df[den_col]) * 100

print(result_df)

方式二:逐行生成单个列的DataFrame

和你原代码逻辑一致,每次循环单独生成仅包含当前计算列的DataFrame:

import pandas as pd

# 数据初始化同上,省略重复代码

# 遍历df1每一行
for idx, row in df1.iterrows():
    col_a = row['A']
    col_b = row['B']
    col_c = row['C']
    
    # 生成单个列的DataFrame
    single_result = pd.DataFrame({col_a: ((df[col_b] / df[col_c]) * 100)})
    
    # 这里可以添加对single_result的后续操作,比如保存、单独分析等
    print(f"第{idx+1}次循环结果:")
    print(single_result)

高效向量化实现(大数据量推荐)

如果你的数据量较大,iterrows()效率偏低,可以用向量化操作一次性完成所有计算:

# 直接批量计算所有列
result_df = df[df1['B']].div(df[df1['C']].values, axis=0) * 100
# 设置结果列名
result_df.columns = df1['A']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:38:28