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

如何在Pandas DataFrame中依据字段映射提取对应列值并替换

在Pandas中根据列名映射替换字段值

先处理列表格式的列值

你的Morning Class和Night Class字段是单元素列表,第一步需要把列表中的字符串提取出来:

import pandas as pd

# 构造你的示例DataFrame
df = pd.DataFrame({
    'id': [1, 2],
    'Math': ['math100', 'math500'],
    'Physics': ['phys300', 'phys250A'],
    'Morning Class': [['Math'], ['Physics']],
    'Night Class': [['Physics'], ['Math']]
})

# 将单元素列表转为字符串
df['Morning Class'] = df['Morning Class'].str[0]
df['Night Class'] = df['Night Class'].str[0]

方法1:使用apply逐行映射(简单直观)

这种方法逻辑清晰,适合小数据集:

# 替换Morning Class的值
df['Morning Class'] = df.apply(lambda row: row[row['Morning Class']], axis=1)
# 替换Night Class的值
df['Night Class'] = df.apply(lambda row: row[row['Night Class']], axis=1)

方法2:使用lookup矢量化操作(高效大数据)

如果你的数据集很大,apply的逐行处理会比较慢,推荐用lookup实现矢量化操作,速度更快:

# 重置索引(确保索引是连续整数,lookup要求索引和列索引匹配)
df_reset = df.reset_index(drop=True)

# 获取每个行对应的目标列的索引位置
morning_col_indices = df_reset.columns.get_indexer(df_reset['Morning Class'])
night_col_indices = df_reset.columns.get_indexer(df_reset['Night Class'])

# 提取对应列的值
df_reset['Morning Class'] = df_reset.lookup(df_reset.index, morning_col_indices)
df_reset['Night Class'] = df_reset.lookup(df_reset.index, night_col_indices)

# 若需要恢复原索引,执行下面一行
# df = df_reset.set_index(df.index)

运行完上述代码后,你就能得到目标DataFrame:

idMathPhysicsMorning ClassNight Class
1math100phys300math100phys300
2math500phys250Aphys250Amath500

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:05:23