How to replace whole NaN cell with pandas DataFrame

I want to replace the entire cell containing the word as circled in the image with spaces or NaN. However, when I try to replace, for example, "1.25 Dividend", it turns out to be "1.25 NaN". I want to return the whole cell as "NaN". Any ideas how to work on this?

My dataframe

+4
source share
3 answers

Option 1
Use regex in your replacement

df.replace('^.*Dividend.*$', np.nan, regex=True)

From the comments

( regex=True) , . . '^' , . '^.*' . '$' . '.*$' . , '^.*Dividend.*$' , 'Dividend' - , . np.nan

df

df = pd.DataFrame([[1, '2 Dividend'], [3, 4], [5, '6 Dividend']])
df

   0           1
0  1  2 Dividend
1  3           4
2  5  6 Dividend

   0    1
0  1  NaN
1  3  4.0
2  5  NaN

2
pd.DataFrame.mask applymap.
lambda applymap, , 'Dividend'.

df.mask(df.applymap(lambda s: 'Dividend' in s if isinstance(s, str) else False))

   0    1
0  1  NaN
1  3    4
2  5  NaN

3
, stack/unstack + pd.Series.str.contains

df.mask(df.stack().astype(str).str.contains('Dividend').unstack())

   0    1
0  1  NaN
1  3    4
2  5  NaN
+4

:

df.apply(lambda x: pd.to_numeric(x, errors='coerce'))
0

I would use applymap like this

df.applymap(lambda x: 'NaN' if (type(x) is str and 'Dividend' in x) else x)
0
source

Source: https://habr.com/ru/post/1680904/


All Articles