PdF
PdF

Reputation: 77

Insert values in data-frame's new columns on the right index

I would like to obtain the lower_bound of some datas and insert it into a new column on the relative index. for example:

My df:
        col1  col2
    0     1     3
    1     2     4
    2     5     8
    3     1     2
    4     8     4
    5     6     2
    6     4     8
    7     8     6
    8     6     4
    9     5     9


lower_bound = 0.1
df['newcol']=df[(df.col1 == 8)].col2.quantile(lower_bound)

this is my output:

        col1  col2  newcol
     0     1     3    4.02
     1     2     4    4.02
     2     5     8    4.02
     3     1     2    4.02
     4     8     4    4.02
     5     6     2    4.02
     6     4     8    4.02
     7     8     6    4.02
     8     6     4    4.02
     9     5     9    4.02   

But i would like to obtain:

         col1  col2  newcol
     0     1     3    
     1     2     4    
     2     5     8    
     3     1     2    
     4     8     4    4.02
     5     6     2    
     6     4     8    
     7     8     6    4.02
     8     6     4    
     9     5     9  

Thank you very much in advance!

Upvotes: 1

Views: 38

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Also this:

In [728]: val = df[(df.col1 == 8)].col2.quantile(lower_bound)
In [741]: val
Out[741]: 4.2

In [745]: df.loc[(df.col1 == 8),'newcol'] = val

In [746]: df
Out[746]: 
    col1  col2  newcol
0    1.0   3.0     NaN
1    2.0   4.0     NaN
2    5.0   8.0     NaN
3    1.0   2.0     NaN
4    8.0   4.0     4.2
5    6.0   2.0     NaN
6    4.0   8.0     NaN
7    8.0   6.0     4.2
8    6.0   4.0     NaN
9    5.0   9.0     NaN

Upvotes: 1

jezrael
jezrael

Reputation: 862441

Assign output to filtered new column:

lower_bound = 0.1
m = df.col1 == 8
df.loc[m, 'newcol'] = df.loc[m, 'col2'].quantile(lower_bound)
#another solution
#df['newcol'] = np.where(m, df.loc[m, 'col2'].quantile(lower_bound), np.nan)

print (df)
0     1     3     NaN
1     2     4     NaN
2     5     8     NaN
3     1     2     NaN
4     8     4     4.2
5     6     2     NaN
6     4     8     NaN
7     8     6     4.2
8     6     4     NaN
9     5     9     NaN

Upvotes: 1

Related Questions