0

Here is my issue, I have a dataframe, let's say:

df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})

I also have a list of index:

idx = [1, 2]

I would like to store in a list, the corresponding value in each column. Meaning I want the first value of the col1 and the second value of the col2.

I'm sure there is a simple answer to my issue however I'm mixing everything up with iloc and cannot find a way of developing a optimized method in my case (I have 1000 rows and 4 columns).

0

3 Answers 3

1

IIUC, you can try:

you can extract the complete rows and then pick the diagonal elements

result = np.diag(df.values[idx])

Alternative:

  1. convert the dataframe to numpy array.
  2. use numpy indexing to access the required values.
result = df.values[idx, range(len(df.columns))]

OUTPUT:

array([6, 3])
Sign up to request clarification or add additional context in comments.

2 Comments

In fact, converting the dataframe to a numpy array solves the issue I expressed in the comment of @AnuragDabas.
So, If I'm not wrong you need this - np.diag(df.values[idx]) ??
1

Use:

list(df.values[idx, range(len(idx))])

Output:

[6, 3]

Comments

0

Here is a different way:

df.stack().loc[list(zip(idx,df.columns[:(len(idx))]))].to_numpy()

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.