How do I mutate a Pandas DataFrame with a series of dictionaries.
Given the following DataFrame:
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# add dict series
df = df.assign(my_dict="{}")
df.my_dict = df.my_dict.apply(json.loads)
| Name | Age | my_dict |
|---|---|---|
| tom | 10 | {} |
| nick | 15 | {} |
| juli | 14 | {} |
How would I operate on column my_dict and mutate it as follows:
Age > 10
| Name | Age | my_dict |
|---|---|---|
| tom | 10 | {"age>10": false} |
| nick | 15 | {"age>10": true} |
| juli | 14 | {"age>10": true} |
And then mutate again:
Name = "tom":
| Name | Age | my_dict |
|---|---|---|
| tom | 10 | {"age>10": false, "name=tom": true} |
| nick | 15 | {"age>10": true, "name=tom", false} |
| juli | 14 | {"age>10": true, "name=tom", false} |
I'm interested in the process of mutating the dictionary, the rules are arbitrary examples.
"{}"is a string, not a dictionary, 2- you do not explain where the new data should come from. Ideally you should create this column only once as the operation of mutating it will be expensivejson.loadsto transform the string. The new data comes from the conditions which are clearly described in the question.df = df.assign(my_dict="{}")