Home > Software engineering >  Pandas : How to Apply a Condition on Every Values of a Dataframe, Based on a Second Symmetrical Data
Pandas : How to Apply a Condition on Every Values of a Dataframe, Based on a Second Symmetrical Data

Time:11-23

I have a dictionary with 2 DF : "quantity variation in %" and "prices". They are both symmetrical DF.

Let's say I want to set the price = 0 if the quantity variation in percentage is greater than 100 %

import numpy as np;   import pandas as pd

d = {'qty_pct': pd.DataFrame({ '2020':   [200, 0.5, 0.4],
                               '2021':   [0.9, 0.5, 500],
                               '2022':   [0.9, 300, 0.4]}),
     'price':   pd.DataFrame({ '2020':   [-6, -2, -9],
                               '2021':   [ 2,  3,  4],
                               '2022':   [ 4,  6,  8]})}

# I had something like that in mind ...

df = d['price'].applymap(lambda x: 0 if x[d['qty_pct']] >=1 else x)

P.S. If by any chance there is a way to do this on asymmetrical DF, I would be curious to see how it's done. Thanks,

I want to obtain this DF :

price = pd.DataFrame({'2020':   [ 0, -2, -9],
                      '2021':   [ 2,  3,  0],
                      '2022':   [ 4,  0,  8]})

CodePudding user response:

Assume price and qty_pct always have the same dimension, then you can just do:

d['price'][d['qty_pct'] >= 1] = 0

d['price']
   2020  2021  2022
0     0     2     4
1    -2     3     0
2    -9     0     8
  • Related