我怎么知道熊猫数据框单元格的类型

Joh*_*ith 4 python excel dataframe pandas

我有一个数据框,例如:

1
1.3
2,5
4
5
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我想知道我的 Pandas 数据帧的不同单元格的类型是什么:

for i in range (len(data.columns)) :
                print (" lenth of  columns : " + str(len(data.columns)) )
                for j in range (len(data[i])) :
                    data[i][j]=re.sub(r'(\d*)\.(\d*)',r'\1,\2',str(data[i][j]))
                    print(str(data[i][j]))

                    print(" est de type : "type(data[i][j]))
                    if str(data[i][j]).isdigit():
                        print(str(data[i][j]) + " contain a number  " )
Run Code Online (Sandbox Code Playgroud)

问题是当数据帧的一个单元格包含一个点时,pandas 认为它​​是一个字符串。所以我使用了正则表达式,以便将点更改为逗号。

但在那之后,我所有数据帧单元格的类型都更改为字符串。我的问题是:我怎么知道数据帧的单元格是 int 还是 float?我已经试过了isinstance(x, int)

编辑:如何计算 int 和 float 的数量,例如 df.apply(type) 的输出,我想知道我的列中有多少个单元格是 int 或 float

我的第二个问题是,为什么当我有 2.5 时,数据框给他 str 类型?

    0       <class 'int'>
1       <class 'str'>
2     <class 'float'>
3     <class 'float'>
4       <class 'int'>
5       <class 'str'>
6       <class 'str'>
Run Code Online (Sandbox Code Playgroud)

谢谢。

raf*_*elc 11

如果您有不同类型的列,例如

>>> df = pd.DataFrame(data = {"l": [1,"a", 10.43, [1,3,4]]})
>>> df
           l
0          1
1          a
2      10.43
4  [1, 3, 4]
Run Code Online (Sandbox Code Playgroud)

Pandas 只会声明这Series是 dtype object。但是,您可以通过简单地应用type函数来获取每个条目类型

>>> df.l.apply(type)
0     <type 'int'>
1     <type 'str'>
2     <type 'float'>
4     <type 'list'>
Run Code Online (Sandbox Code Playgroud)

但是,如果您有一个数据类型非常不同的数据集,您可能应该重新考虑其设计。

  • @demongolem如果你想要每个单元格,请使用`df.applymap(type)` (2认同)