Home > database >  Pandas: Get column dtype as string
Pandas: Get column dtype as string

Time:01-12

Given a series and the (unique) dtype of a column, I would like the dtype information inside as a string.

import numpy as np
import pandas as pd

df = pd.DataFrame(columns = ['col1', 'col2'], data = [[1,2], [3,4]])
df.dtypes[0]

The output of code above

Sample output of code above

Goal: Extract the string 'int64' from df.dtypes[0], which is dtype('int64').

Have not been successful in finding a solution online.

CodePudding user response:

Simply convert to string:

df.dtypes.astype(str)[0]

Or if you're really only interested in a single value, use the name attribute.

df.dtypes[0].name

Output: 'int64'

For the whole Series:

>>> df.dtypes.astype(str)
col1    int64
col2    int64
dtype: object
  •  Tags:  
  • Related