Python Forum

Full Version: check pandas variable type
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to check variable's data type is list or dataframe.
When I got type(df_c) is Out[155]: pandas.core.frame.DataFrame.
Checking it again by type(df_c) == 'pandas.core.frame.DataFrame', it showed False, not True. <-- I think it should print "True" rather than "False".

import pandas as pd

c=[1,2,3]

df_c=pd.DataFrame(c)

type(df_c)
Out[155]: pandas.core.frame.DataFrame

type(df_c) == 'pandas.core.frame.DataFrame'
Out[156]: False
you compare type of the object with str object - that's why it's false.
As per the docs and also PEP8 recommendation, the isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

import pandas as pd
 
spam = [1,2,3]
df = pd.DataFrame(spam)

# better use isinstance()
print(isinstance(df, pd.DataFrame))
print(isinstance(spam, list))
Oh! I just got a lesson by isinstance this function.
Thank for your assistance.

(Jun-12-2020, 08:47 AM)buran Wrote: [ -> ]you compare type of the object with str object - that's why it's false.
As per the docs and also PEP8 recommendation, the isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

import pandas as pd
 
spam = [1,2,3]
df = pd.DataFrame(spam)

# better use isinstance()
print(isinstance(df, pd.DataFrame))
print(isinstance(spam, list))
just for brevity, although not recommended using type will work like this
print(type(df_c) == pd.DataFrame)