1

I have data as

[{'name': 'A', 'subsets': ['X_1', 'X_A', 'X_B'], 'cluster': 0},
 {'name': 'B', 'subsets': ['B_1', 'B_A'], 'cluster': 2},
 {'name': 'C', 'subsets': ['X_1', 'X_A', 'X_B'], 'cluster': 0},
 {'name': 'D', 'subsets': ['D_1', 'D_2', 'D_3', 'D_4'], 'cluster': 1}]

I need to represent it as

Cluster Number    Subset                         Name
0                 ['X_1', 'X_A', 'X_B']          A, C
1                 ['D_1', 'D_2', 'D_3', 'D_4']   D
2                 ['B_1', 'B_A']                 B 

2 Answers 2

1

For the sake of completeness, I think it is fair to mention that you can actually create a dataframe without json_normalize in your case and apply groupby as originally shown here:

import pandas as pd

data = [{'name': 'A', 'subsets': ['X_1', 'X_A', 'X_B'], 'cluster': 0},
 {'name': 'B', 'subsets': ['B_1', 'B_A'], 'cluster': 2},
 {'name': 'C', 'subsets': ['X_1', 'X_A', 'X_B'], 'cluster': 0},
 {'name': 'D', 'subsets': ['D_1', 'D_2', 'D_3', 'D_4'], 'cluster': 1}]

df = pd.DataFrame(data).groupby('cluster')
                       .agg({'subsets':'first','name':', '.join})
                       .reset_index()
                       .set_index('cluster')
                       .rename_axis('Cluster Number')
                             subsets  name
Cluster Number                            
0                    [X_1, X_A, X_B]  A, C
1               [D_1, D_2, D_3, D_4]     D
2                         [B_1, B_A]     B
Sign up to request clarification or add additional context in comments.

Comments

1

You can use json_normalize + groupby "cluster" and apply join to "name" and first to "subsets":

df = pd.json_normalize(data).groupby('cluster').agg({'subsets':'first','name':', '.join}).reset_index()

Output:

   cluster               subsets  name
0        0       [X_1, X_A, X_B]  A, C
1        1  [D_1, D_2, D_3, D_4]     D
2        2            [B_1, B_A]     B

1 Comment

Kindly check the edited question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.