使用索引列表访问pandas数据框中的条目 [英] Access entries in pandas data frame using a list of indices

查看:272
本文介绍了使用索引列表访问pandas数据框中的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是,我只需要分配在不同行和列上的原始数据帧的子集。例如:

I facing the issue that I need only a subset of a my original dataframe that is distributed over different rows and columns. E.g.:

# My Original dataframe
import pandas as pd
dfTest = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])

输出:

   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

我可以提供一个包含行和列索引的列表,其中我想要的值是位于:

I can provide a list with rows and column indices where my desired values are located:

array_indices = [[0,2],[1,0],[2,1]]

我想要的输出是一系列:

My desired output is a series:

3
4
8

任何人都可以提供帮助?

Can anyone help?

推荐答案

使用 pd.DataFrame.lookup

dfTest.lookup(*zip(*array_indices))

array([3, 4, 8])

您可以将其包装在 pd.Series 构造函数中

Which you can wrap in a pd.Series constructor

pd.Series(dfTest.lookup(*zip(*array_indices)))

0    3
1    4
2    8
dtype: int64






轻微变体


Slight variant

i, j = np.array(array_indices).T
dfTest.values[i, j]

array([3, 4, 8])

同样如上所述

pd.Series(dfTest.values[i, j])

0    3
1    4
2    8
dtype: int64

这篇关于使用索引列表访问pandas数据框中的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆