如何按指定索引顺序从DataFrame的指定列提取对应数据
解决方案
你可以直接用pandas内置的reindex方法或者loc索引实现需求,操作非常简单:
- 如果你需要得到list类型的结果:
# 方法1:使用reindex(更推荐自定义索引排序场景) result = df['values'].reindex(order).tolist() # 方法2:使用loc索引 result = df.loc[order, 'values'].tolist()
- 如果你需要得到numpy array类型的结果:
# 方法1:使用reindex result = df['values'].reindex(order).to_numpy() # 方法2:使用loc索引 result = df.loc[order, 'values'].to_numpy()
注意:如果你的
order列表里包含DataFrame索引中不存在的值,对应位置会返回NaN,你可以根据需求加dropna()处理缺失值。
内容的提问来源于stack exchange,提问作者Ryszard Eggink
相关产品推荐
相关产品推荐

