首页 > 解决方案 > 如何在 DataFrame 列中查找所有唯一数据类型?

问题描述

例如:

df = pd.DataFrame([[int(1),2,3],[int(5),6,'a'],[0.1,4,True]], columns = list("abc"))
df
   a    b  c
0  1.0  2  3
1  5.0  6  a
2  0.1  4  True

(附带问题:为什么不声明int做任何事情?)

现在,df.dtypes回归

a    float64
b      int64
c     object
dtype: object

但是是否有可能在一列中列出所有不同的数据类型?

喜欢

a    int64, float64
b    int64
c    int64, str, bool

标签: pythonpandasdataframetypes

解决方案


您可以使用.applymap(type)原始数据框中的各个值的类型来取回数据框:

df = pd.DataFrame([[1, 2, 3],[5, 6, 'a'],[0.1, 4, True]], columns = list("abc"))

print(df.applymap(type))

输出

                 a              b               c
0  <class 'float'>  <class 'int'>   <class 'int'>
1  <class 'float'>  <class 'int'>   <class 'str'>
2  <class 'float'>  <class 'int'>  <class 'bool'>

附带问题:为什么不声明int做任何事情?)

Python中没有“声明”这样的东西。int(1)(几乎)没有什么不同1。列a显示为,float64因为最后一个元素是0.1。这会导致pandas转换15float(因为0.1不能转换为int)。


推荐阅读