Home > OS >  Replace Values in Column Based on values in a list in Pandas with nan without using for loop
Replace Values in Column Based on values in a list in Pandas with nan without using for loop

Time:08-31

I have a dataframe. test = {'x': [1.1, 1.2, 0.15, 20], 'y': [-111,, -20, -1.9, -80]} df = pd.DataFrame(test)

I also have another list which contains some numbers, ls=[1.2, 0.15, 2.2]. I would like to replace element in "x" columns of df which has same values as "ls" with nan. Therefore, I write using for loop.

for i in ls:
    df.loc[df['x'] == i, 'x'] = np.nan

I would like to know whether there are other way to achieve the same purpose without using for loop to replace some values in dataframe with nan?

Expected output: | Index | x | y | |:----- |:---|:--- | |0. |1.1 |-111 | |1. |nan |-20. | |2. |nan |-1.9 | |3. |20. |-80. |

Thanks.

CodePudding user response:

Use Series.isin for check membership:

df.loc[df['x'].isin(ls), 'x'] = np.nan

Another idea with Series.mask:

df['x'] = df['x'].mask(df['x'].isin(ls))

CodePudding user response:

You can also use Series.replace:

df.x.replace(map(np.nan, ls))
  • Related