Home > database >  Python dataframe to list/dict
Python dataframe to list/dict

Time:11-29

I have a sample dataframe as below

Column_Name     Datatype
FirstName       string
LastName        string
Department      integer
EmployeeID      string

I want this dataframe converted to this below format in python so I can pass it into dtype

{ 'FirstName':'string', 'LastName':'string', 'Department':'integer', 'EmployeeID':'string', }

Could anyone please let me know how this can be done.

To note above: I need the exact string {'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'} from the exact dataframe.

The dataframe has list of primary key names and its datatype. I want to pass this primary_key and datatype combination into concat_df.to_csv(csv_buffer, sep=",", index=False, dtype = {'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'})

CodePudding user response:

dict/zip the two series:

import pandas as pd

data = pd.DataFrame({
    'Column_Name': ['FirstName', 'LastName', 'Department', 'EmployeeID'],
    'Datatype': ['string', 'string', 'integer', 'string'],
})

mapping = dict(zip(data['Column_Name'], data['Datatype']))

print(mapping)

prints out

{'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'}

CodePudding user response:

use to record which is much more handy.

print(dict(df.to_records(index=False)))

Should Gives #

{'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'}

Edit :

If you want keys alone then

d = dict(df.to_records(index=False))

print(list(d.keys()))

should Gives #

['FirstName', 'LastName', 'Department', 'EmployeeID']

CodePudding user response:

You can do an easy dict comprehension with your data:

Input data: data = pd.DataFrame({'Column_Name' : ['FirstName', 'LastName', 'Department'], 'Datatype' : ['Jane', 'Doe', 666]})

Dict comprehension:

{n[0]:n[1] for n in data.to_numpy()}

This will give you:

{'FirstName': 'Jane', 'LastName': 'Doe', 'Department': '666'}

There are for sure other ways, e.g. using the pandas to_dict function, but I am not very familiar with this.

Edit: But keep in mind, a dictionary needs unique values. Your categories (first, lastname) looks like general categories. This here will only work for a single person, otherwise you have multiple keys.

  • Related