Saranya V
Saranya V

Reputation: 11

Fetch a column according to List in a python pandas dataframe

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?

Upvotes: 1

Views: 74

Answers (1)

jezrael
jezrael

Reputation: 862791

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]

Upvotes: 2

Related Questions