Home > other >  Is there a Pandas function to get the data types of the elements of dataframe as a new dataframe?
Is there a Pandas function to get the data types of the elements of dataframe as a new dataframe?

Time:12-08

I am trying to get the datatypes of all the elements in a dataframe into a new dataframe and was wondering if there is a native Pandas function for this case?

Example:

import pandas as pd

d = {'col1': [1, '2', 2.0, []], 'col2': [3, '4', 4.0, []]}
df = pd.DataFrame(data=d)
  col1 col2
0    1    3
1    2    4
2    2    4
3   []   []

Expected result:

    col1   col2
0    int    int
1    str    str
2  float  float
3   list   list

CodePudding user response:

Use DataFrame.applymap with type:

df = df.applymap(type)
print (df)
              col1             col2
0    <class 'int'>    <class 'int'>
1    <class 'str'>    <class 'str'>
2  <class 'float'>  <class 'float'>
3   <class 'list'>   <class 'list'>

If need remove class use lambda function with __name__

df = df.applymap(lambda x: type(x).__name__)
print (df)
    col1   col2
0    int    int
1    str    str
2  float  float
3   list   list
  • Related