2017-09-04 44 views
1

如何根据索引和标头列表从数据帧中获取值?根据索引和另一个值访问数据帧中的值

这些都是dataframes我有:

a = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=['a','b','c']) 
referencingDf = pd.DataFrame(['c','c','b']) 

基于同样的指数,我试图得到以下数据帧输出:

outputDf = pd.DataFrame([3,6,8]) 

目前,我试过,但需要取对角线值。敢肯定有这样做的更好的办法:

a.loc[referencingDf.index.values, referencingDf[:][0].values] 
+0

等等,你是否想要'a [referencingDf [0]]'? – DyZ

+0

yeap,多数民众赞成在正确的! – smallcat31

+0

然后,你又有什么问题了? – DyZ

回答

2

IIUC,你可以在列表解析使用df.get_value

vals = [a.get_value(*x) for x in referencingDf.reset_index().values] 
# a simplification would be [ ... for x in enumerate(referencingDf[0])] - DYZ 
print(vals) 
[3, 6, 8] 

然后构造一个数据帧。

df = pd.DataFrame(vals) 
print(df) 

    0 
0 3 
1 6 
2 8 
+0

'... for枚举中的x(referencingDf [0])'? – DyZ

+0

@DYZ绝对是另一种选择,假设'referencingDf'具有列的rangeIndex(可能不总是如此)。 –

2

使用列表理解另一种方式:

vals = [a.loc[i,j] for i,j in enumerate(referencingDf[0])] 
# [3, 6, 8] 
4

您需要lookup

b = a.lookup(a.index, referencingDf[0]) 
print (b) 
[3 6 8] 

df1 = pd.DataFrame({'vals':b}, index=a.index) 
print (df1) 
    vals 
0  3 
1  6 
2  8 
0

下面是一个使用column_index,然后索引NumPy's advanced-indexing一个量化的方法和提取过各的值一排数据帧 -

In [177]: col_idx = column_index(a, referencingDf.values.ravel()) 

In [178]: a.values[np.arange(len(col_idx)), col_idx] 
Out[178]: array([3, 6, 8]) 
相关问题