Skip to main content
 首页 » 编程设计

python之根据另一个数据框中的索引和值访问数据框中的值

2025年05月04日10findumars

如何根据索引和 header 列表从数据框中获取值?

这些是我的数据框:

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] 

请您参考如下方法:

你需要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