Why is my code dropping the values when creating a dataframe out of a dictionary?

Viewed 29

In my program, I am trying to create a dataframe which consists of users and a few pieces of information like Username, Role, Status, etc. I'm trying to create a blank list, then update it with pieces of information from various APIs. Once I have all the info inputted, the Dict is turned into a dataframe and which is then used elsewhere in the code.

However, it seems when I create a Dictionary, update the values, then create a Dataframe out of it, the values of each key are dropped. I want each key to be a column.

Code:

import pandas as pd

SimpleDict = {
        "Username":[],
        'Role':[],
        'User Status':[],
        'laptop Status':[],
        'Laptop Serial':[],
        'Error':[]
    }
SimpleDict.update({'Username': 'Goose'})
SimpleDict.update({'User Status': 'Active'})
SimpleDict.update({'Role': 'CEO'})

print(SimpleDict)

df = pd.DataFrame.from_dict(SimpleDict)

print(df)

Expected/Desired Output:

0 Username - Role - User Status - Laptop Status - Laptop Serial - Error
1 Goose    - CEO  - Active      -               -               -           

Actual Output:

Empty DataFrame
Columns: [Username, Role, User Status, laptop Status, Laptop Serial, Error]
Index: []
1 Answers

Create an empty dataframe with specified columns,

df = pd.DataFrame(columns=['Username', 'Role', 'User Status', 'laptop Status', 'Laptop Serial', 'Error'])



Method 1

df.loc[0,['Username','Role','User Status']] = ['Goose', 'CEO', 'Active']
df
###
  Username Role User Status laptop Status Laptop Serial Error
0    Goose  CEO      Active           NaN           NaN   NaN

Method 2

df = pd.concat([df, pd.DataFrame({'Username':['Goose'], 'Role':['CEO'], 'User Status':['Active']})])
df
###
  Username Role User Status laptop Status Laptop Serial Error
0    Goose  CEO      Active           NaN           NaN   NaN

Note: pandas.DataFrame.append() is deprecated since pandas version 1.4.0

Related