列出数据框列中存在的所有数据类型

x89*_*x89 2 python types data-analysis dataframe pandas

如何列出数据框df的Name列中存在的所有数据类型?

Name
1.0
XCY
Run Code Online (Sandbox Code Playgroud)

有些可能是字符串,有些可能是浮点数等。

U10*_*ard 5

Try using map, agg or apply:

>>> df['Name'].map(type).value_counts()
<class 'float'>    1
<class 'str'>      1
Name: Name, dtype: int64
Run Code Online (Sandbox Code Playgroud)
>>> df['Name'].agg(type).value_counts()
<class 'float'>    1
<class 'str'>      1
Name: Name, dtype: int64
Run Code Online (Sandbox Code Playgroud)
>>> df['Name'].apply(type).value_counts()
<class 'float'>    1
<class 'str'>      1
Name: Name, dtype: int64
>>> 
Run Code Online (Sandbox Code Playgroud)

To get the actual type names, use:

>>> df['Name'].map(lambda x: type(x).__name__).value_counts()
float    1
str      1
Name: Name, dtype: int64
>>> 
Run Code Online (Sandbox Code Playgroud)

You can change map to apply or agg and the code would still work as expected.

I use type.__name__ to get the type name, more about it in the documentation here:

The name of the class, function, method, descriptor, or generator instance.