Ouakrat
Ouakrat

Reputation: 97

Reshape pandas dataframe which has dict as values

I have a pandas dataframe which has dict as values. I would like to transform this dataframe into the format in expected result.

image of the df i have

and i want to split the columns into each keys of the dict. For example for the first columns 'questionnaire', i want 'questionnaire.step', 'questionnaire.lastCompletedStep' and so on.

the issue here it's that json normalization doesn't works:

json_normalize(data=data)

someone know how to fix it?

Upvotes: 0

Views: 151

Answers (1)

Kaushik Dayalan
Kaushik Dayalan

Reputation: 66

Is the column value in the format of type string ? If it is then you can try this. I tried this on a dataframe and it worked. Iterate over each column values convert them from str to dict then iterate over those values create a new column with key value and assign the value to the column.

data  =  [str({"step": 7, "lastCompletedStep": 7})]
df = pd.DataFrame(data, columns=["questionaire"])
df

enter image description here

dataval = df.questionaire[0]
print(type(dataval))

enter image description here

result = eval(dataval)
print(result)
print(type(result))

enter image description here

for i,(k, v) in enumerate(result.items()):
df["questionaire"+"."+str(k)] = v
df

enter image description here

Upvotes: 1

Related Questions