Links

Check Columns type

Tags: #pandas #snippet #datacleaning #operations
Author: Florent Ravenel
Description: This notebook checks columns in a dataframe. It could be very usefull to apply specific rules regarding columns format.

Input

Import libraries

import pandas as pd

Setup DataFrame

# create DataFrame
df = pd.DataFrame(
{
"team": ["A", "A", "A", "B", "B", "B"],
"points": [11, 7, 8, 10, 13, 13],
"assists": [5, 7, 7, 9, 12, 9],
"rebounds": [11, 8, 10, 6, 6, 5],
}
)
df

View DataFrame format

df.info()

Model

Check Columns type in dataframe and create conditions

for c in df.columns:
print(f"Columns '{c}' is {df[c].dtype}.")
if df[c].dtype == object:
print(f"=> Do something")
elif df[c].dtype == str:
print(f"=> Do something")
elif df[c].dtype == int:
print(f"=> Do something")
elif df[c].dtype == float:
print(f"=> Do something")

Output

View new DataFrame format

df.info()