2

I have dataframe (in a matrix form) where each cell is either 0 or {}. I want to replace the {} for 1.

I tried the following:

df.replace({},1)

and

for col in df:
    for i, val in enumerate(col):
        if df[col][i] == {}:
            df[col][i] = 1

Both are not working. There are no errors, just the {} does not get replace. Is there an issue with {} ? I got this matrix by applying pd.DataFrame(some dictionary).

2
  • replace will not work here as it is for strings. Commented Apr 22, 2014 at 20:20
  • enumerate is the wrong thing to do here, you should use iterrows or iteritems but the best thing to do is create the boolean mask and then just set the values Commented Apr 22, 2014 at 20:33

2 Answers 2

3

Use boolean indexing to locate where you have matches and set the value:

In [2]:

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

Out[2]:

    a   b
0   0  {}
1  {}   0
2   0   0

[3 rows x 2 columns]

In [19]:

for col in df:
    df[col][df[col]=={}]=1

df

Out[19]:

   a  b

0  0  1
1  1  0
2  0  0

[3 rows x 2 columns]

EDIT

Better is to do the mask on the entire dataframe, also you shouldn't perform chain indexing, thanks @Jeff for pointing out the error in my ways:

In [35]:

df[df=={}]=1

df

Out[35]:

   a  b
0  0  1
1  1  0
2  0  0

[3 rows x 2 columns]
Sign up to request clarification or add additional context in comments.

1 Comment

@Jeff I've updated my answer, I think I did try that initally and it gave me an error, I think it was a syntax error but I just tried it again and it worked so I've updated my answer
0

Try this:

for col in df:
    for i in range(0,len(col)):
        if col[i] == {}:
            col[i] = 1

replace will not work as it is a built-in that operates on strings. The only problem with your second method is that you were using the values of each column instead of the indices.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.