baxx
baxx

Reputation: 4725

How to replace an empty dict with a values in pandas

I have the following:

pd.DataFrame({
    'a' : { 1 : {}},
    'b' : {1 : 3}
})

Which looks as :

    a  b
1  {}  3

And would like to be able to replace the {} with 0, or NaN, I'm not sure how to go about doing so though. I can't use .replace it seems

pd.DataFrame({
    'a' : { 1 : {}},
    'b' : {1 : 3}
}).replace({ {} : 0})

Gives an error

Upvotes: 1

Views: 1488

Answers (4)

RichieV
RichieV

Reputation: 5183

Since a dictionary is not hashable, .replace cannot act on in, however pandas has a function to handle iterables: .explode

print(df.explode('a'))
     a  b
1  NaN  3

It will still work if instead of being empty, the dictionary has 0-based consecutive integers keys (0, 1, n-1):

df = pd.DataFrame({
    'a' : {1 : {0: 'row0', 1: 'row1'}},
    'b' : {1 : 3}
})

print(df.explode('a'))
      a  b
1  row0  3
1  row1  3

It will raise an exception if the dictionary is not empty or if the keys are not strictly continuous and 0-based (e.g. {2: val, 'string_key':val, -1:val} will cause explode to fail due to all three keys)

Upvotes: 0

Daweo
Daweo

Reputation: 36640

This:

pd.DataFrame({
    'a' : { 1 : {}},
    'b' : {1 : 3}
}).replace({ {} : 0})

cause error because dict's keys must be hashable - {} is not. In such case you might use pandas.DataFrame.replace with two lists of equal length, following way:

import pandas as pd
df = pd.DataFrame({
    'a' : { 1 : {}},
    'b' : {1 : 3}
}).replace([{}],[0])
print(df)

Output:

   a  b
1  0  3

Upvotes: 0

Ayoub ZAROU
Ayoub ZAROU

Reputation: 2417

you could do:

df = pd.DataFrame({
    'a' : { 1 : {}},
    'b' : {1 : 3}
})
df.applymap((lambda x: 0 if x == {} else x))

Upvotes: 0

BENY
BENY

Reputation: 323326

You can use bool , when there is empty dict it will return False

df=df.where(df.astype(bool),0)

df
Out[26]: 
   a  b
1  0  3

Upvotes: 5

Related Questions