【问题标题】:How can I know the type of a pandas dataframe cell我怎么知道熊猫数据框单元格的类型
【发布时间】:2018-09-30 07:13:03
【问题描述】:

我有一个数据框,例如:

1
1.3
2,5
4
5

通过以下代码,我想知道我的 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  " )

问题是当数据框的一个单元格包含一个点时,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'>

谢谢。

【问题讨论】:

标签: python excel pandas dataframe


【解决方案1】:

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

>>> 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]

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

>>> df.l.apply(type)
0     <type 'int'>
1     <type 'str'>
2     <type 'float'>
4     <type 'list'>

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

【讨论】:

  • 谢谢,我想知道为什么在我的熊猫数据框中,带有点的数字 2.5 是
  • 2.5 是一个浮点数; "2.5" 是一个字符串。 Pandas 默认将您的文件读取为 str,您必须手动将所有数字转换为浮点数/整数。 Pandas 通常能正确推断类型。但是混合类型很难做到。
  • 很好的答案,但我相信 OP 要求的是整个数据框,而不仅仅是一列。例如,如果我执行df.apply(type),它将打印出每一列的类型,而不是每个单元格的类型。
  • @demongolem 如果你想要每个单元格,请使用df.applymap(type)
猜你喜欢
  • 2015-02-06
  • 2022-01-12
  • 2016-01-28
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
相关资源
最近更新 更多