【问题标题】:Fastest way to find all data types in a pandas series?查找熊猫系列中所有数据类型的最快方法?
【发布时间】:2019-04-19 07:08:54
【问题描述】:

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

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

目前我被困在:

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

但是我每次都写这个累了,所以我想知道是否有更好的方法。

【问题讨论】:

标签: python pandas types


【解决方案1】:

我们可以使用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]

【讨论】:

  • 也可以s.apply(type).value_counts(),会显示系列中每种类型的计数。
  • @Erfan 第一种写起来比较快,但是后一种差不多
猜你喜欢
  • 2021-09-12
  • 2019-07-04
  • 2022-10-16
  • 2023-03-28
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
相关资源
最近更新 更多