Python熊猫插入长整数

Tom*_*Tom 5 python numpy pandas

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

dei*_*aur 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)]
Run Code Online (Sandbox Code Playgroud)

然后我尝试:

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)
Run Code Online (Sandbox Code Playgroud)

请注意dtypeofDataFrame与第 94 行中请求的不匹配。正如我在上面的评论中所写,numpy 数组工作得很好。此外,如果您uint32在第 94 行中指定,它仍然指定 a dtypeofint64DataFrame。但是,它不会给您带来负溢出,可能是因为uint32适合 的正值int64