昨天我问了一个很漂亮answered by @jezrael
的问题他用这个:
df = pd.DataFrame([[1, 0, 1], [1, 1, 0], [0, 1, 1], [0, 0, 1]])
print (df.T.dot(1 << np.arange(df.shape[0] - 1, -1, -1)))
0 12
1 6
2 11
dtype: int64
1 << np.arange(df.shape[0])
适用于df.shape[0]
不到30小时,但在此之后会爆炸。考虑到int32或int64的数据类型,这也是可以理解的。会有一个限制。但是,当我只使用<<
操作数执行左移int
时,它会返回long
并保持准确性。如何使用numpy获得与使用1 << 60
时相同的结果?
这是我跑的地方:
import numpy as np
for n in range(0, 61, 10):
a = np.arange(n + 1, dtype=int)
pstr = "for n = {:<5d}; 1 << a[-1] = {:<12d}; 1 << n = {:<12d}"
print pstr.format(n, 1 << a[-1], 1 << n)
for n = 0 ; 1 << a[-1] = 1 ; 1 << n = 1
for n = 10 ; 1 << a[-1] = 1024 ; 1 << n = 1024
for n = 20 ; 1 << a[-1] = 1048576 ; 1 << n = 1048576
for n = 30 ; 1 << a[-1] = 1073741824 ; 1 << n = 1073741824
for n = 40 ; 1 << a[-1] = 256 ; 1 << n = 1099511627776
for n = 50 ; 1 << a[-1] = 262144 ; 1 << n = 1125899906842624
for n = 60 ; 1 << a[-1] = 268435456 ; 1 << n = 1152921504606846976
答案 0 :(得分:4)
您必须将int32数组转换为python对象数组:
numbers = np.arange(100,dtype=int)
longs = 1 << np.arange(100).astype(object)