【问题标题】:Python pandas insert long integerPython pandas插入长整数
【发布时间】:2012-11-13 02:36:42
【问题描述】:

我正在尝试在 Pandas 数据框中插入长整数

import numpy as np
from pandas import DataFrame

data_scores = [(6311132704823138710, 273), (2685045978526272070, 23), (8921811264899370420, 45), (17019687244989530680L, 270), (9930107427299601010L, 273)]
dtype = [('uid', 'u8'), ('score', 'u8')]
data = np.zeros((len(data_scores),),dtype=dtype)
data[:] = data_scores
df_crawls = DataFrame(data)
print df_crawls.head()

但是当我查看数据框时,最后一个很长的值现在是负数:

uid分数 0 6311132704823138710 273 1 2685045978526272070 23 2 8921811264899370420 45 3 -1427056828720020936 270 4 -8516636646409950606 273

uid 是 64 位无符号整数,所以 'u8' 应该是正确的 dtype 吗?有什么想法吗?

【问题讨论】:

  • 似乎溢出了。尝试“更大”的数据类型怎么样?
  • 使用 u16 : TypeError: 数据类型不理解
  • 你的 np-data 看起来很好,错误表明 pandas 错过了 u 并给你一个有符号的长而不是无符号的。
  • 我最好的猜测是,numpy 可能会保留数组中每个元素所需的位数,而 pandas 可能使用 c,在这种情况下,例如 a 的大小。长期依赖于您的系统架构(32 位与 64 位)。所以简而言之,问题可能是在 32 位计算机上运行您的代码。

标签: python numpy pandas


【解决方案1】:

这不会告诉您该怎么做,除非在 64 位计算机上尝试或联系 pandas 开发人员(或自己修补问题......)。但无论如何,这似乎是你的问题:

问题是DataFrame 不理解 unsigned int 64 位,至少在 32 位机器上是这样。

我更改了您的 data_score 的值,以便更好地跟踪正在发生的事情:

data_scores = [(2**31 + 1, 273), (2 ** 31 - 1, 23), (2 ** 32 + 1, 45), (2 ** 63 - 1, 270), (2 ** 63 + 1, 273)]

然后我尝试了:

In [92]: data.dtype
Out[92]: dtype([('uid', '<u8'), ('score', '<u8')])

In [93]: data
Out[93]: 
array([(2147483649L, 273L), (2147483647L, 23L), (4294967297L, 45L),
       (9223372036854775807L, 270L), (9223372036854775809L, 273L)], 
      dtype=[('uid', '<u8'), ('score', '<u8')])

In [94]: df = DataFrame(data, dtype='uint64')

In [95]: df.values
Out[95]: 
array([[2147483649,                  273],
       [2147483647,                   23],
       [4294967297,                   45],
       [9223372036854775807,                  270],
       [-9223372036854775807,                  273]], dtype=int64)

注意DataFramedtype 与第 94 行中请求的不匹配。另外,正如我在上面的评论中所写,numpy 数组可以完美运行。此外,如果您在第 94 行中指定 uint32,它仍会为 DataFrame 值指定 dtypeint64。但是它不会给你负溢出,可能是因为uint32 适合int64 的正值。

【讨论】:

  • 我个人认为这是熊猫中的一个错误,应该报告。 Pandas 至少应该在从 numpy 进行这种不安全的强制转换时发出警告,并在使用不同类型然后明确要求时发出错误......
  • 我同意它会更好,还值得注意的是,它实际上会为您的数据创建一个新副本,因此如果数组很大,您将使用两倍的内存...
【解决方案2】:

是的——这是 pandas 目前的限制——我们确实计划在未来添加对无符号整数 dtypes 的支持。错误消息会更好:

http://github.com/pydata/pandas/issues/2355

现在您可以将dtype=object 列作为一种解决方法。

编辑 2012-11-27

现在检测溢出,但现在将变为 dtype=object,直到 DataFrame 更好地支持无符号数据类型。

In [3]: df_crawls
Out[3]: 
                    uid  score
0   6311132704823138710    273
1   2685045978526272070     23
2   8921811264899370420     45
3  17019687244989530680    270
4   9930107427299601010    273

In [4]: df_crawls.dtypes
Out[4]: 
uid      object
score     int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多