Aly
Aly

Reputation: 367

How to replace values in Pandas Dataframe in a loop?

I have Pandas Dataframe which look like this:

       feat_1   feat_2  feat_3  ...  ... 
target  10       23       15    
UL      0.5      4        7 
LL     -0.5     -4       -7

Where UL and LL stands for upper and lower limit and this is index. I want in loop replace values of those with calculated limits like this:

for col in df.columns:
    UL = df[column].loc['target'] + df[column].loc['UL']
    LL = df[column].loc['target'] + df[column].loc['LL']

   ??? 

So my desired output would look like this:

       feat_1   feat_2  feat_3  ...  ... 
target  10       23       15    
UL      10.5     27       22    
LL      9.5      19       8

Upvotes: 1

Views: 299

Answers (1)

jezrael
jezrael

Reputation: 862481

You can use non loop solution like using only DataFrame.loc:

df.loc[['UL', 'LL']] += df.loc['target']
print (df)
        feat_1  feat_2  feat_3
target    10.0    23.0    15.0
UL        10.5    27.0    22.0
LL         9.5    19.0     8.0

working like:

df.loc[['UL', 'LL']] = df.loc[['UL', 'LL']] + df.loc['target']

Upvotes: 2

Related Questions