Home > Back-end >  a dataframe having dictionary , i want dataframe in such a way that dictionary's key becomes th
a dataframe having dictionary , i want dataframe in such a way that dictionary's key becomes th

Time:09-06

{'BLOCKER': 'F', 'CRITICAL': 'E', 'MAJOR': 'D', 'MINOR': 'B', 'NO RISK': 'A'} 

this is the dictionary and is inside a column called severity ,

dataframe i want is

A              B          C            D            E           F

NO RISK      MINOR        NA         MAJOR        CRITICAL    BLOCKER

CodePudding user response:

This should do it

df.severity.apply(pd.Series)

CodePudding user response:

A straightforward solution:

input_map = {'BLOCKER': 'F', 'CRITICAL': 'E', 'MAJOR': 'D', 'MINOR': 'B', 'NO RISK': 'A'}

inv_map = {v: k for k, v in input_map.items()}  # {'F': 'BLOCKER', 'E': 'CRITICAL', 'D': 'MAJOR', 'B': 'MINOR', 'A': 'NO RISK'}

pd.DataFrame({k: [inv_map.get(k, 'NA')] for k in 'ABCDEF'})
         A      B   C      D         E        F
0  NO RISK  MINOR  NA  MAJOR  CRITICAL  BLOCKER

CodePudding user response:

import pandas as pd

mdi = {"BLOCKER": ["F"], "CRITICAL": ["E"], "MAJOR": ["D"], "MINOR": ["B"], "NO RISK": ["A"]}

pd.DataFrame.from_records({v[0]: [k] for k, v in mdi.items()})

Output:

         A      B      D         E        F
0  NO RISK  MINOR  MAJOR  CRITICAL  BLOCKER

You'll need to apply this yourself to your column in the source data.

CodePudding user response:

If you have a Series of dictionaries as input, use:

df2 = pd.json_normalize(df['severity'])

cols = df2.groupby(np.zeros(len(df2))).first().squeeze()

df2 = (df2
       .notna().mul(cols.index)
       .set_axis(cols, axis=1)
       .rename_axis(columns=None)
       )

Output:

           F         E      D      B        A
0    BLOCKER  CRITICAL  MAJOR  MINOR  NO RISK

Used input:

dic = {'BLOCKER': 'F', 'CRITICAL': 'E', 'MAJOR': 'D', 'MINOR': 'B', 'NO RISK': 'A'} 

df = pd.DataFrame({'severity': [dic]})

Example of output on an input with several rows:

         F         E      D      B        A      O
0  BLOCKER  CRITICAL  MAJOR  MINOR  NO RISK       
1  BLOCKER  CRITICAL         MINOR  NO RISK  OTHER
``
  • Related