1

This is what my dataframe looks like, How can i fetch column b of the dataframe where a=[98,43,23,2,5] such that it returns [12,39,23,32,78]

a   b   c
2   32  34
5   78  23
98  12  11
23  23  66
43  39  43

I want to write a method that takes in a list(to compare with column a), and returns a list back(corresponding values of b) from the dataframe.

def get_reordered_b_according_to_a(a_list):
    #code 
    return reordered_list_b

How can I do this efficiently?

1 Answer 1

2

Use DataFrame.set_index with DataFrame.reindex, if some value ixist in list and not in column a is returned NaNs:

a=[98,43,23,2,5]

def get_reordered_b_according_to_a(a_list):
    return df.set_index('a').b.reindex(a_list).tolist()
print (get_reordered_b_according_to_a(a))
[12, 39, 23, 32, 78]

a=[43,23,2,5,7]
def get_reordered_b_according_to_a(a_list):
    return df.set_index('a').b.reindex(a_list).tolist()
print (get_reordered_b_according_to_a(a))
[39.0, 23.0, 32.0, 78.0, nan]
Sign up to request clarification or add additional context in comments.

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.