Python | Pandas Categorical DataFrame Creation

Code :

# Python code explaining
# building a categorical data frame

 
# importing libraries

import numpy as np

import pandas as pd

 
# Build data frame

data = { 'col1' : [ 1 , 2 , 4 , 5 ], 'col2' : [ 3 , 4 , 5 , 6 ]}

df1 = pd.DataFrame (data = data)

 

print ( "df1:" , df1)

print ( " df1 type: " , df1.dtypes)

Output:

# Convert data frame to category

df2 = pd.DataFrame ({ 'A' : list ( '1245' ), 'B' : list ( ' 3456' )}, dtype = "category" )

 

print ( "df2:" , df2)

print ( "df2 type:" , df2.dtypes)

 

print ( "df2 column 0:" , df2 [ 'A' ])

print ( "df2 column 1:" , df2 [ 'B' ])

Output:

# Conversion can be done with astype ()

df3 = pd.DataFrame ({ 'A' : list ( 'efgh' ), 'B' : list ( 'aebc' )})

print ( "df3:" , df3)

print ( "df3 type:" , df3.dtypes)

 

df4 = df3.astype ( 'category' )

print (< / code> "df4 type:" , df4.dtypes)

Output:





Get Solution for free from DataCamp guru