简体   繁体   中英

Pandas: How to replace values to np.nan based on Condition for multiple columns

Here is my dataframe.

I  A  B  C  D  E  F
1  9  4  0  T  F  F
2  0  5  1  S  X  J
3  1  8  0  G  G  J

Here is my expected output. I want to replace if value in A ==0, repalce to np.nan in D.

I  A   B   C   D   E   F
1  9   4   0   T   F   nan
2  0   5   1   nan X   J
3  1   8   0   G   G   nan

I want to replace values on D/E/F columns by values of A/B/C columns. For example, D column changes according to the A column. (A->D, B->E, C->F)

I tried this code but didn't change value.

list1 = ['A', 'B', 'C']
list2 = ['D', 'E', 'F']

for i in list2:
    for j in list1:
        df[i] = np.where(df[j] == 0, np.nan, df[i])

For below code, working well. But there are lots of columns, so I want to using list and for sentence.

df['D'] = np.where(df.A == 0, np.nan, df.D)

First we create a dictionary from your two lists using zip

replace_dict = dict(zip(list1,list2))

then we loop over it to handle your assignments,

for k,v in replace_dict.items():
    df.loc[df[k] == 0, v] = np.nan

print(df)
   I  A  B  C    D  E    F
0  1  9  4  0    T  F  NaN
1  2  0  5  1  NaN  X    J
2  3  1  8  0    G  G  NaN

another method is to use np.where with your lists.

df[list2] = np.where(df[list1].eq(0), np.nan,df[list2])

print(df)

   I  A  B  C    D  E    F
0  1  9  4  0    T  F  NaN
1  2  0  5  1  NaN  X    J
2  3  1  8  0    G  G  NaN

Let us do

df.loc[:,'D':].mask(df.loc[:,'A':'C'].eq(0).values)
     D  E    F
0    T  F  NaN
1  NaN  X    J
2    G  G  NaN
df.loc[:,'D':]= df.loc[:,'D':].mask(df.loc[:,'A':'C'].eq(0).values)

Use DataFrame.mask with DataFrame.rename as:

df[list2] = df[list2].mask(df[list1].rename(columns=dict(zip(list1, list2))).eq(0))

print(df)
   I  A  B  C    D  E    F
0  1  9  4  0    T  F  NaN
1  2  0  5  1  NaN  X    J
2  3  1  8  0    G  G  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