Home > Software engineering >  Formatting a DataFrame to columns and rows, using python
Formatting a DataFrame to columns and rows, using python

Time:10-22

I have this DataFrame:

518    {'idSite': 108660, 'accessLevel': 1, 'owner': ...
519    {'idSite': 99068, 'accessLevel': 1, 'owner': T...
520    {'idSite': 96393, 'accessLevel': 1, 'owner': T...
521    {'idSite': 47832, 'accessLevel': 0, 'owner': T...
522    {'idSite': 67643, 'accessLevel': 1, 'owner': T...
Name: records, Length: 523, dtype: object

I'd like to format it to a table where the keys (idSite, accessLevel, owners, etc) are the column header, and the values (108660, 1 and True, etc) are the respective cell values.

How do I do this using python?

CodePudding user response:

I assume the values in your DataFrame are strings that look like a dictionary, a way is to create a new dataframe with the evaluated values of the dict.

pd.DataFrame(data = [eval(i[0]) for i in records.values],index = records.index)

I advise you to review the creation of your DataFrame, remember you can create a DataFrame from a nested dictionary and it will give the desired result inmediatly:

records = pd.DataFrame({
518:{'idSite': 108660, 'accessLevel': 1, 'owner': True},
519:{'idSite': 99068, 'accessLevel': 1, 'owner': True},
520:{'idSite': 96393, 'accessLevel': 1, 'owner':True},
521:{'idSite': 47832, 'accessLevel': 0, 'owner': False},
522:{'idSite': 67643, 'accessLevel': 1, 'owner': False}
            }).T

CodePudding user response:

records = pd.DataFrame({
518:{'idSite': 108660, 'accessLevel': 1, 'owner': True},
519:{'idSite': 99068, 'accessLevel': 1, 'owner': True},
520:{'idSite': 96393, 'accessLevel': 1, 'owner':True},
521:{'idSite': 47832, 'accessLevel': 0, 'owner': False},
522:{'idSite': 67643, 'accessLevel': 1, 'owner': False}
                       })

val1 = json.loads(json.dumps(records))



abc = pd.DataFrame(val1, columns=[
        "idSite",
        "accessLevel",
        "owner",])

The Output of the above gives me exactly what I wanted

     idSite  accessLevel  owner    
0      6354            0   True  
1    130450            1   True  
2    117886            1   True  
3    127354            1   True  
4    120436            1   True  
  • Related