[英]Access entries in pandas data frame using a list of indices
I facing the issue that I need only a subset of a my original dataframe that is distributed over different rows and columns. 我面临的问题是,我只需要分配在不同行和列上的原始数据帧的子集。 Eg: 例如:
# My Original dataframe
import pandas as pd
dfTest = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
Output: 输出:
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? 有人可以帮忙吗?
Use pd.DataFrame.lookup
使用pd.DataFrame.lookup
dfTest.lookup(*zip(*array_indices))
array([3, 4, 8])
Which you can wrap in a pd.Series
constructor 您可以将其包装在pd.Series
构造函数中
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])
Similarly as above 与上面类似
pd.Series(dfTest.values[i, j])
0 3
1 4
2 8
dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.