Home > Net >  Replace values of empty dictionaries in a dataframe column
Replace values of empty dictionaries in a dataframe column

Time:11-06

Given the following:

data = pd.DataFrame({"a": [{}, 1, 2]})

How best to replace {} with a particular value?

The following works:

rep = 0
data.apply(lambda x: [y if not isinstance(y, dict) else rep for y in x])

but I'm wondering if there's something more idiomatic.

CodePudding user response:

Try with bool empty object will return False

data.loc[~data.a.astype(bool),'a'] = 0 
data
Out[103]: 
   a
0  0
1  1
2  2

CodePudding user response:

You can use pd.to_numeric with errors='coerce':

In [24]: data['a'] = pd.to_numeric(data['a'], errors='coerce').fillna(0).astype(int)

In [25]: data
Out[25]: 
   a
0  0
1  1
2  2
  • Related