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

Pandas中如何通过索引列表提取对应值列表的元素?

解决Pandas中按行提取列表指定索引元素的问题

你的需求是对DataFrame每一行,从df['all']的列表中提取df['ind']列表里索引对应的元素——比如第0行df['ind'] = [1,2],要从[0,2,3]里取出索引1和2的元素得到[2,3]。

你之前的代码错误在于:用df['ind'].apply()时,lambda里的df.at[i, 'all']是取第i行的all列,而非当前行all列表中索引为i的元素。

正确代码示例

import pandas as pd
df = pd.DataFrame([[0, 2, 3], [5, 6, 5], [10, 20, 30]],index=[0, 1, 2], columns=['A', 'B', 'C'])
df['all'] = df.apply(lambda x: [i for i in x], axis=1)
e = pd.Series([[1,2],[0], [1,3]], index=[0, 1, 2])
df = df.assign(ind=e.values)

# 核心修正:通过axis=1的apply同时访问每行的all和ind列
df['values'] = df.apply(lambda row: [row['all'][idx] for idx in row['ind']], axis=1)

print(df)

输出结果

A   B   C           all     ind  values
0   0   2   3     [0, 2, 3]  [1, 2]  [2, 3]
1   5   6   5     [5, 6, 5]     [0]     [5]
2  10  20  30  [10, 20, 30]  [1, 3]  [20]

注:第2行ind包含索引3,但row['all']的长度为3(最大索引是2),因此仅能提取到索引1的元素20。若要避免索引越界,可添加判断逻辑:[row['all'][idx] for idx in row['ind'] if idx < len(row['all'])]

效率优化方案

如果数据量较大,apply的效率可能偏低,可改用列表推导式实现相同逻辑,速度更快:

df['values'] = [
    [all_list[idx] for idx in ind_list] 
    for all_list, ind_list in zip(df['all'], df['ind'])
]

内容的提问来源于stack exchange,提问作者Muhammad Usman Rafique

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:07:20