Find all columns of dataframe in Pandas whose type is float, or a particular type? Find all columns of dataframe in Pandas whose type is float, or a particular type? python python

Find all columns of dataframe in Pandas whose type is float, or a particular type?


This is conciser:

# select the float columnsdf_num = df.select_dtypes(include=[np.float])# select non-numeric columnsdf_num = df.select_dtypes(exclude=[np.number])


You can see what the dtype is for all the columns using the dtypes attribute:

In [11]: df = pd.DataFrame([[1, 'a', 2.]])In [12]: dfOut[12]:    0  1  20  1  a  2In [13]: df.dtypesOut[13]: 0      int641     object2    float64dtype: objectIn [14]: df.dtypes == objectOut[14]: 0    False1     True2    Falsedtype: bool

To access the object columns:

In [15]: df.loc[:, df.dtypes == object]Out[15]:    10  a

I think it's most explicit to use (I'm not sure that inplace would work here):

In [16]: df.loc[:, df.dtypes == object] = df.loc[:, df.dtypes == object].fillna('')

Saying that, I recommend you use NaN for missing data.


As @RNA said, you can use pandas.DataFrame.select_dtypes. The code using your example from a question would look like this:

for col in df.select_dtypes(include=['object']).columns:    df[col] = df[col].fillna('unknown')