class_id | class | code | id |
---|---|---|---|
8 | XYZ | A | 1 |
8 | XYZ | B | 2 |
9 | ABC | C | 3 |
I have a dataframe like above. I want to transform it so the ‘codes’ column below collects all the unique (code, id) pairs into a JSON format that a class contains.
class_id | class | codes |
---|---|---|
8 | XYZ | [{‘code: ‘A’, ‘id’: 1}, {‘code’: ‘B’, ‘id’: 2}] |
9 | ABC | [{‘code: ‘C’, ‘id’: 3}] |
Advertisement
Answer
This approach should works for you:
JavaScript
x
12
12
1
import pandas as pd
2
3
records = {"class": ["XYZ", "XYZ", "ABC"], "code": ["A", "B", "C"], "id": [1, 2, 3]}
4
df = pd.DataFrame(records)
5
pd.DataFrame(
6
[
7
(x[0], x[1].drop(columns=["class"]).to_dict(orient="records"))
8
for x in df.groupby("class")
9
],
10
columns=["class", "codes"],
11
)
12