0

How can I write a for loop to check types of columns in a dataframe one by one? For example, for below df:

enter image description here

Any help would be great!

ShazAl
  • 35
  • 3

1 Answers1

1

Edit based on comment

A simpler version based on @NewbieAF's comment: df.dtypes


This should do it {c: df[c].dtype for c in df.columns}

Example:

import pandas as pd
data = [{'age': 20, 'name': 'james', 'gpa': 18.5},
        {'age': 21, 'name': 'anna', 'gpa': 19.6},
        {'age': 18, 'name': 'sam', 'gpa': 17.0}]

df = pd.DataFrame(data)
print({c: df[c].dtype for c in df.columns})

Result: {'age': dtype('int64'), 'name': dtype('O'), 'gpa': dtype('float64')}

Rodrigo Cava
  • 173
  • 9
  • 2
    wouldn't `df.dtypes` be simpler? –  Apr 22 '22 at 23:45
  • 1
    Indeed! Also learning new things here, haha. Thanks for the feedback – Rodrigo Cava Apr 22 '22 at 23:56
  • Thanks! I see that my question is not straightforward. I want to write a for loop to replace the missing values of each column with the mean of the values in that column. However, the problem will be that some of these columns might be string, object, etc. This is the reason I am looking for a way to check each column type so I could write it as an if ... else... statement. – ShazAl Apr 23 '22 at 14:48