Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access values in a dataframe based on index and values in another

How do i get the value from a dataframe based on a list of index and headers?

These are the dataframes i have:

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

Based on the same index, i am trying to get the following dataframe output:

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

Currently, i tried this but would need to take the diagonal values. Am pretty sure there is a better way of doing so:

a.loc[referencingDf.index.values, referencingDf[:][0].values]
like image 216
smallcat31 Avatar asked Dec 31 '25 15:12

smallcat31


1 Answers

You need 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
like image 133
jezrael Avatar answered Jan 03 '26 05:01

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!