如何在DataFrame列中查找所有唯一数据类型?

时间:2019-02-02 16:53:08

标签: python pandas dataframe types

例如:

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

1 个答案:

答案 0 :(得分:1)

可以使用.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。这导致pandas15转换为float(因为0.1无法转换为int)。