I've got a pandas DataFrame that looks like this:
molecule species
0 a dog
1 b horse
2 c []
3 d pig
4 e []
I want to replace the []
value with NaN
using python. How can I achieve this?
For testing:
df = pd.DataFrame({
'molecule': ['a','b','c','d','e'],
'species' : ['horse','cat','[]','frog','lion']})
CodePudding user response:
You can try this
import numpy as np
df = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : ['horse','cat','[]','frog','lion']})
df["species"].replace({"[]":np.nan})
replace
will take dictionary where you can tell what to be mapped to what.
CodePudding user response:
You can also replace values with NAN with DataFrame.mask()
methods. The mask() method replaces the values of the rows where the condition evaluates to True.
import numpy as np
import pandas as pd
df = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : ['horse','cat','[]','frog','lion']})
df=df.mask(df == '[]')
CodePudding user response:
df.loc[df.species.eq('[]'), 'species'] = np.nan