Issue
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.
Solution
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))
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.