Home > front end >  How to transform index values into columns using Pandas?
How to transform index values into columns using Pandas?

Time:05-20

I have a dictionary like this:

my_dict = {'RuleSet': {'0': {'RuleSetID': '0',
   'RuleSetName': 'Allgemein',
   'Rules': [{'RulesID': '10',
     'RuleName': 'Gemeinde Seiten',
     'GroupHits': '2',
     'KeyWordGroups': ['100', '101', '102']}]},
  '1': {'RuleSetID': '1',
   'RuleSetName': 'Portale Berlin',
   'Rules': [{'RulesID': '11',
     'RuleName': 'Portale Berlin',
     'GroupHits': '4',
     'KeyWordGroups': ['100', '101', '102', '107']}]},
  '6': {'RuleSetID': '6',
   'RuleSetName': 'Zwangsvollstr. Berlin',
   'Rules': [{'RulesID': '23',
     'RuleName': 'Zwangsvollstr. Berlin',
     'GroupHits': '1',
     'KeyWordGroups': ['100', '101']}]}}}

When using this code snippet it can be transformed into a dataframe:

rules_pd = pd.DataFrame(my_dict['RuleSet'])
rules_pd

The result is: enter image description here

I would like to make it look like this:

enter image description here

Does anyone know how to tackle this challenge?

CodePudding user response:

Doing from_dict with index

out = pd.DataFrame.from_dict(my_dict['RuleSet'],'index')
Out[692]: 
  RuleSetID  ...                                              Rules
0         0  ...  [{'RulesID': '10', 'RuleName': 'Gemeinde Seite...
1         1  ...  [{'RulesID': '11', 'RuleName': 'Portale Berlin...
6         6  ...  [{'RulesID': '23', 'RuleName': 'Zwangsvollstr....
[3 rows x 3 columns]
#out.columns
#Out[693]: Index(['RuleSetID', 'RuleSetName', 'Rules'], dtype='object')

CodePudding user response:

You could try use Transpose()

rules_pd = pd.DataFrame(my_dict['RuleSet']).transpose()
print(rules_pd)
  • Related