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

如何根据预定义的行、列值从Pandas DataFrame中提取对应数值

你可以直接逐行遍历df2的查询条件,匹配后取值即可,示例实现如下:

import pandas as pd

# 示例数据定义
df = pd.DataFrame({
    'Avg1': [1, 2, 3, 4],
    'Avg2': [3, 5, 1, 15],
    'Date': ['2021-08-06', '2021-08-07', '2021-08-08', '2021-08-07']
})

df2 = pd.DataFrame({
    'Return Avg': ['Avg1', 'Avg2'],
    'At Date': ['2021-08-08', '2021-08-07']
})

# 循环取值逻辑
res = []
for idx, row in df2.iterrows():
    target_col = row['Return Avg']
    target_date = row['At Date']
    # 过滤匹配日期的行,取对应列第一个匹配值
    match_val = df.loc[df['Date'] == target_date, target_col].iloc[0]
    res.append(match_val)

# 写入结果到df2
df2['Returned values (what I want)'] = res
print(df2)

运行后输出结果和预期完全一致:

Return AvgAt DateReturned values (what I want)
0Avg12021-08-083
1Avg22021-08-075

如果是超大数据量场景,可以先对df做索引预处理,大幅降低每次循环的过滤耗时:

# 预处理:将日期设为索引,提升查询速度
df_date_idx = df.set_index('Date')
res = []
for idx, row in df2.iterrows():
    target_col = row['Return Avg']
    target_date = row['At Date']
    match_val = df_date_idx.loc[target_date, target_col].iloc[0]
    res.append(match_val)
df2['Returned values (what I want)'] = res

如果同日期下有多个匹配值需要做聚合计算,把.iloc[0]替换成对应的聚合方法即可,比如.sum()、.max()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:00:04