我有一个DataFrame cd ../nam-1.15/ && make install
:
df1
我需要计算一个名为df1.head() =
wght num_links
id_y id_x
3 133 0.000203 2
186 0.000203 2
5 6 0.000203 2
98 0.000203 2
184 0.000203 2
的变量,
thr
其中thr = N*(N-1)*2,
是N
的行数。
问题在于,当我计算df1
时,Python会抛出一个负值(尽管所有输入都是正数):
thr
可能的提示
行数N是
ipdb> df1['wght'].count()*(df1['wght'].count()-1)*2
-712569744
因此,
ipdb> df1['wght'].count()
137736
考虑到可以分配给ipdb> 137736*137735*2
37942135920.
的最大值是int32
,我怀疑NumPy会考虑2147483647
,它应该是type(thr) = <int32>
。这有意义吗?
请注意,我没有编写生成<int64>
的代码,因为
df1
但是,如果需要重现错误,请告诉我。
提前致谢。
答案 0 :(得分:7)
您遇到np.int32
溢出,因此请使用len(df)
代替df.column.count()
。
这是一个小型演示:
In [149]: x = pd.DataFrame(np.random.randint(0,100,size=(137736, 3)), columns=list('ABC'))
In [150]: x.A.count() * (x.A.count() - 1) * 2
Out[150]: -712569744
In [151]: len(x) * (len(x) - 1) * 2
Out[151]: 37942135920
In [153]: type(x.A.count())
Out[153]: numpy.int32
In [154]: type(len(x))
Out[154]: int
答案 1 :(得分:2)
如果你得到count()
的类型(即type(df1['wght'].count())
),你会收到:
<class 'numpy.int32'>
所以试试你的计算:
n = df1['wght'].count().astype(np.int64)
n*(n-1)*2
答案 2 :(得分:1)
您可以将df1['wght'].count()
传递给像这样的长构造函数,以确保它很长。
N = long(df1['wght'].count())
虽然存储到任何变量
N = df1['wght'].count()
应该工作,因为int类有一个__mul__
方法(实现*),在需要时会创建一个长结果。
Python 3.x还有#34;统一&#34; int和long也负责处理bug。