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

时间:2019-04-18 23:01:58

标签: python pandas types

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

我知道我可以做df.dtypes,但是如果一列同时包含stringint,它只会返回object,这并不是特别有用。

目前,我坚持:

set(type(x) for x in df['column'])

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

1 个答案:

答案 0 :(得分:2)

我们可以使用apply(type)

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

print(s)

0    1
1    2
2    3
3    4
dtype: object

应用类型:

s.apply(type)

0    <class 'str'>
1    <class 'int'>
2    <class 'int'>
3    <class 'str'>
dtype: object

要获取唯一值:

s.apply(type).unique()

array([<class 'str'>, <class 'int'>], dtype=object)

要获得更清晰的列表,请执行以下操作:

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

[str, int]