Get value by filtering for column

Viewed 59

my DataFrame looks basically like this:

> In [2]: fruits = pd.DataFrame({"apple": [1, 1.5, 2], 
   ...:                        "cherry": [2, 3, 1],
   ...:                        "banana": [2, 4, 5], 
   ...:                        "prices": ["apple", "banana", "cherry"]})

In [3]: fruits
Out[3]:

   apple  cherry  banana  prices
0    1.0       2       2   apple
1    1.5       3       4  banana
2    2.0       1       5  cherry

In a new column I want to get the value of the fruit prices from the according columns specfiyed by the values in column prices. This should be the final result:

In [4]: fruits_adjusted = pd.DataFrame({"apple": [1, 1.5, 2],
   ...:                        "cherry": [2, 3, 1], 
   ...:                        "banana": [2, 4, 5], 
   ...:                        "prices": ["apple", "banana", "cherry"], 
   ...:                        "price_fruits": [1, 4, 1]})

In [5]: fruits_adjusted
Out[5]:

   apple  cherry  banana  prices  price_fruits
0    1.0       2       2   apple             1
1    1.5       3       4  banana             4
2    2.0       1       5  cherry             1

Many thanks for the support!

Bye R

2 Answers

TRY:

df['price_fruits'] = df.apply(lambda x : x[x['prices']], 1)

OUTPUT

   apple  cherry  banana  prices  price_fruits
0    1.0       2       2   apple           1.0
1    1.5       3       4  banana           4.0
2    2.0       1       5  cherry           1.0

This question is answered from here.

Here is my solution given the answer voted-up in that question.

Try:

fruits_adjusted["price_fruits"] = fruits_adjusted.lookup(fruits_adjusted.index, fruits_adjusted.prices)

fruits_adjusted["price_fruits"] = fruits_adjusted["price_fruits"].astype("int64")

Output

display(fruits_adjusted)
   apple  cherry  banana  prices  price_fruits
0    1.0       2       2   apple             1
1    1.5       3       4  banana             4
2    2.0       1       5  cherry             1
Related