faraa
faraa

Reputation: 585

read a json column into new columns pandas

I have a column like this in pandas dataframe and I want to convert it to multiple columns a,b,c,d

{"a":false,"b":false}
{"a":false,"b":false,"c":true}
nan
{"a":false}
{"a":true,"d":true}

I tried:

ops = ops.join( pd.DataFrame(json.loads(d)  for d in ops.pop('json_column')) )

but it creates columns with names(a,b,c,d) and doesn't put values into it. All values are nan.

Upvotes: 1

Views: 126

Answers (1)

jezrael
jezrael

Reputation: 863751

For me working your solution with if-else statement for handle missing values and also is added [] with index parameter:

ops = ops.join(pd.DataFrame([json.loads(d) 
                             if pd.notna(d) 
                             else {} 
                             for d in ops.pop('json_column')], index=ops.index))
print (ops)
       a      b     c     d
0  False  False   NaN   NaN
1  False  False  True   NaN
2    NaN    NaN   NaN   NaN
3  False    NaN   NaN   NaN
4   True    NaN   NaN  True

Upvotes: 1

Related Questions