查找 pandas 系列中所有数据类型的最快方法?

cal*_*Guy 4 python types pandas

显示 pandas 系列中所有值类型的最快方法是什么?

我知道我可以只执行df.dtypes,但如果列同时具有stringint,它只会返回object,这并不是特别有帮助。

目前我陷入困境:

set(type(x) for x in df['column'])
Run Code Online (Sandbox Code Playgroud)

但是我每次都厌倦了写这个,所以我想知道是否有更好的方法来做到这一点。

Erf*_*fan 9

我们可以用apply(type)

s = pd.Series(['1', 2, 3, '4'])

print(s)

0    1
1    2
2    3
3    4
dtype: object
Run Code Online (Sandbox Code Playgroud)

申请类型:

s.apply(type)

0    <class 'str'>
1    <class 'int'>
2    <class 'int'>
3    <class 'str'>
dtype: object
Run Code Online (Sandbox Code Playgroud)

要获得唯一值:

s.apply(type).unique()

array([<class 'str'>, <class 'int'>], dtype=object)
Run Code Online (Sandbox Code Playgroud)

要获得更清晰的列表:

[x for x in s.apply(type).unique()]

[str, int]
Run Code Online (Sandbox Code Playgroud)

  • 还可以执行`s.apply(type).value_counts()`,它将显示该系列中每种类型的计数。 (2认同)