baxx
baxx

Reputation: 4725

Replace values of empty dictionaries in a dataframe column

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.

Upvotes: 0

Views: 36

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34086

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

Upvotes: 1

BENY
BENY

Reputation: 323326

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

Upvotes: 1

Related Questions