2

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]
4
  • Wait, are you trying to get a[referencingDf[0]]? Commented Sep 4, 2017 at 3:50
  • yeap, thats right! Commented Sep 4, 2017 at 3:53
  • Then, what's your question, again? Commented Sep 4, 2017 at 3:53
  • How i can reference a to get the following outputDf based on referencingDF. essentially a[0]['c'], a[1]['c'], a[2]['b']. Commented Sep 4, 2017 at 3:55

4 Answers 4

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

Another way to use list comprehension:

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

Comments

2

IIUC, you can use df.get_value in a list comprehension.

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]

And then, construct a dataframe.

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

   0
0  3
1  6
2  8

2 Comments

... for x in enumerate(referencingDf[0]) ?
@DYZ Definitely another choice, assuming referencingDf has a rangeIndex for columns (might not always be so).
0

Here's one vectorized approach that uses column_index and then NumPy's advanced-indexing for indexing and extracting those values off each row of dataframe -

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.