Luckyboy. Jupiterchen
Luckyboy. Jupiterchen

Reputation: 39

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

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.

Upvotes: 1

Views: 1414

Answers (1)

jezrael
jezrael

Reputation: 863196

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))

Upvotes: 1

Related Questions