0

I have just started using pandas dataframes and I wanted to know if there is a way to get a value in column, by knowing values of different columns?

Let's suppose a dataframe (df), with the following columns. In the case that I have one value from 'u' and 'v' example u = 123 and v = 962.

Is there a way to get value in column B corresponding to thoses values ?

df = pd.DataFrame({'A':[30, 2, 12, 4, 32, 33, 69],
                   'B':['valx', 'valy', 'valz', 'val45', 'val78', 'val516', 'val123'],
                   'C':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
                   'D':[165, 70, 120, 80, 180, 172, 150],
                   'u':[147,258,369,123,893,123,879],
                   'v':[123,456,789,741,852,963,369]
                   },
                  index=['123', '456', '483', '861', '789', '963', '753'])
       A       B        C       D        u   v

123    30     valx     165     Steak    147 123
456    2      valy     70      Lamb     258 456
483    12     valz     120     Mango    369 789
861    4      val45    80      Apple    123 741
789    32     val78    180     Cheese   893 852
963    33     val516   172     Melon    123 963
753    69     val12    150     Beans    879 369

Currently to solve this problem I do the following code, I am sur that there is prefered way ... :-/

extrait = df[(df['u'] == 123 ) & (df['v'] == 962)]
Val_in_B = extrait['B'][0]
Val_in_B
>>>  val516
FChm
  • 2,515
  • 1
  • 17
  • 37
harry
  • 31
  • 6
  • Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas) – FChm Mar 29 '19 at 15:04

1 Answers1

0

More or less. In fact, as you select the row with a condition, you might have 0, 1, or many values. That is the reason why the selection of one single column will give you a series.

But you can do one single extraction that way:

df.loc[(df.u==123)&(df.v==963), 'B']

It then only make sense to take the first element if you are sure that the search will return exactly one value.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252