Home > Net >  Get the dtype of specific column with a loop
Get the dtype of specific column with a loop

Time:03-08

I want to display all my column with the dtypes. For this I used to do df.dtypes. But in this dataframe I have 4000 column and I would also like to number them.

I tried something like this:

for i in range(df.shape[1]):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None):
        print(i ,':',df.dtypes)

This obviously does not give me the expected result but you get the idea of what I need. How can I can use df.dtypes in a loop?

CodePudding user response:

you can try this:

for i in range(df.shape[1]):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None):
        print(i ,':',df.iloc[:,i].dtypes)

If you want column name also, then try this:

for i in range(df.shape[1]):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None):
        print(i ,':',df.columns[i],df.iloc[:,i].dtypes)

CodePudding user response:

I'm not 100% sure what you want, but this will print the column number (or some version of it), name and dtype, for the whole dataframe:

for i, (name, dtype) in enumerate(zip(df.columns, df.dtypes)):
    print(i, name, dtype)

CodePudding user response:

If you want to print dtypes of all the columns, you can simply do print(df.dtypes) (but it also print dtype: object at the end).

If you want to print it as your own format, such as using :, you can do, as follows:

import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [1.1, 2.2, 3.3]
})

print(df)
#   A  B    C
#0  1  a  1.1
#1  2  b  2.2
#2  3  c  3.3

print(df.dtypes)
#A      int64
#B     object
#C    float64
#dtype: object

for col_name, dtype in df.dtypes.items():
    print(col_name, ":", dtype)

#A : int64
#B : object
#C : float64
  • Related