Write a python function that will taken in a df (dataframe) and return a dictionary with the corresponding data types. You may need to instantiate an empty dictionary in your function. The keys will be the column headers of the df and the values will be the data types.
Code:
import pandas as pd
sample_dataframe = pd.DataFrame()
sample_dataframe['Name'] = ['Mike','Aston']
sample_dataframe['Age'] = [24,22]
sample_dataframe['Address'] = ['CA','NY']
def datatype_dict(dataframe):
# get the columns name of the dataframe
column = list(dataframe.columns)
# get the datatype of each items of each columns
datatypes = [type(dataframe[col][0]) for col in column] # using list comprehension
# creating a dictionary now
dict_datatype = {}
for loop1 in range(len(column)):
dict_datatype[column[loop1]] = datatypes[loop1]
return(dict_datatype)
# calling the function
datatype_dict(sample_dataframe)
Result:
Get Answers For Free
Most questions answered within 1 hours.