Create a custom column in a dict format
Question:
I currently have a dataframe like this
Person
Analysis
Dexterity
Skills
174
3.76
4.12
1.20
239
4.10
3.78
3.77
557
5.00
2.00
4.40
674
2.23
2.40
2.80
122
3.33
4.80
4.10
I want to add an column to compile all this information like below
Person
Analysis
Dexterity
Skills
new_column
174
3.76
4.12
1.20
{"Analysis":"3.76", "Dexterity":"4.12", "Skills":"1.20"}
239
4.10
3.78
3.77
{"Analysis":"4.10", "Dexterity":"3.78", "Skills":"3.77"}
557
5.00
2.00
4.40
{"Analysis":"5.00", "Dexterity":"2.00", "Skills":"4.40"}
674
2.23
2.40
2.80
{"Analysis":"2.23", "Dexterity":"2.40", "Skills":"2.80"}
122
3.33
4.80
4.10
{"Analysis":"3.33", "Dexterity":"4.80", "Skills":"4.10"}
Answers:
You can use to to_dict
method like so:
import pandas as pd
rows = [
{'a': 1, 'b': 2},
{'a': 3, 'b': 4},
]
df = pd.DataFrame(rows)
# define new column as the json format of another
# also convert to str as that is what you have in your output
df['c'] = df[['a', 'b']].astype(str).to_dict(orient='records')
to_dict
has a really nice interface for transforming to JSON format or to other object types. In this instance you are looking for orient='records'
which is a list of dictionaries.
In your case, you will use:
df['new_column'] = df[
['Analysis', 'Dexterity', 'Skills']
].astype(str).to_dict(orient='records')
I currently have a dataframe like this
Person | Analysis | Dexterity | Skills |
---|---|---|---|
174 | 3.76 | 4.12 | 1.20 |
239 | 4.10 | 3.78 | 3.77 |
557 | 5.00 | 2.00 | 4.40 |
674 | 2.23 | 2.40 | 2.80 |
122 | 3.33 | 4.80 | 4.10 |
I want to add an column to compile all this information like below
Person | Analysis | Dexterity | Skills | new_column |
---|---|---|---|---|
174 | 3.76 | 4.12 | 1.20 | {"Analysis":"3.76", "Dexterity":"4.12", "Skills":"1.20"} |
239 | 4.10 | 3.78 | 3.77 | {"Analysis":"4.10", "Dexterity":"3.78", "Skills":"3.77"} |
557 | 5.00 | 2.00 | 4.40 | {"Analysis":"5.00", "Dexterity":"2.00", "Skills":"4.40"} |
674 | 2.23 | 2.40 | 2.80 | {"Analysis":"2.23", "Dexterity":"2.40", "Skills":"2.80"} |
122 | 3.33 | 4.80 | 4.10 | {"Analysis":"3.33", "Dexterity":"4.80", "Skills":"4.10"} |
You can use to to_dict
method like so:
import pandas as pd
rows = [
{'a': 1, 'b': 2},
{'a': 3, 'b': 4},
]
df = pd.DataFrame(rows)
# define new column as the json format of another
# also convert to str as that is what you have in your output
df['c'] = df[['a', 'b']].astype(str).to_dict(orient='records')
to_dict
has a really nice interface for transforming to JSON format or to other object types. In this instance you are looking for orient='records'
which is a list of dictionaries.
In your case, you will use:
df['new_column'] = df[
['Analysis', 'Dexterity', 'Skills']
].astype(str).to_dict(orient='records')