简体   繁体   中英

Replace values by NaN in certain rows of a pandas df given a specific condition in another df

I have this initial df

xpos = pd.DataFrame({'N': [1, 2, 3, 4],'Type': [External, External, Internal, Internal]})

And then I have this other one

L = pd.DataFrame({'N': [1, 2, 3, 4],'Length': [100, 300, 400, 200]})

In dataframe 'L' I need to change the values in column named 'Length' by 'NaN' for every row in first dataframe 'xpos' defined as 'External'. This means substituting 100 and 300 by 'NaN'. This is meant to work with a larger dataframe so I cannot change the values individually and it should detect which value of the 'N' column is external and change its length to 'NaN'

I have tried with a loop for but it is not going well

for i in range (0, len(xpos)):       
    if xpos.loc[i,'Type'] == 'External':
        VLDext=xpos.loc[i, 'N']
        L.loc[VLDext, 0]='NaN'    
      

Of what I have understood, we are based on the values of xpos Type as External we need to update Length column in L as nan .

We are merging L and xpos on column N and then based on Type External in xpos we are updating Length of L by nan .

Code

L['Length'] = np.where(L.merge(xpos, on='N', how='inner').Type == 'External',np.nan,L.Length)

Output

    N   Length
0   1   NaN
1   2   NaN
2   3   400.0
3   4   200.0

Assuming the two data frames have the same length and are aligned on N :

mask = xpos['Type'] == 'External'
L.loc[mask, 'Length'] = np.nan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM