简体   繁体   English

要将 numpy 数组从 bool 转换为 int,我应该乘以 1 还是使用 astype(int)?

[英]To cast a numpy array from bool to int, should I multiply by one or use astype(int)?

bool_array * 1 and bool_array.astype(int) appear to do the same thing. bool_array * 1bool_array.astype(int)似乎做同样的事情。 Which is more efficient?哪个更有效率?

bool_array.astype(int) is faster ( Colab notebook ): bool_array.astype(int)更快( Colab 笔记本):

import numpy as np

bool_array = np.random.choice([0, 1], size=1_000_000).astype(bool)
%timeit int_array = bool_array * 1

1000 loops, best of 5: 1.5 ms per loop 1000 次循环,5 次中的最佳:每个循环 1.5 毫秒

%timeit int_array = bool_array.astype("int")

1000 loops, best of 5: 973 µs per loop 1000 个循环,5 个循环中的最佳:每个循环 973 µs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 astype(int) 将 numpy 数组转换为整数在 Python 3.6 上不起作用 - Converting a numpy array to integer with astype(int) does not work on Python 3.6 如何将int numpy数组的列乘以float数字并保持int? - How can I multiply column of the int numpy array to the float digit and stays in int? 与astype(int)相比,numpy / / rint变慢 - numpy around/rint slow compared to astype(int) 根据规则“安全”,无法将数组数据从dtype('float64')转换为dtype('int64')! int和float之间的astype函数 - Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' ! astype function between int and float 从 int 到 float 的 Numpy 数组 - Numpy array from int to float 为什么在检查“是否为真”之前必须将 int 转换为 bool? - Why must I cast int to bool before checking "is True"? int()与.astype('int')Python - int() vs .astype('int') Python 解决 Pandas 中的 Windows-numpy astype(int) 错误 - Working Around the Windows-numpy astype(int) Bug in Pandas 如何在nopython模式下将浮点numpy数组值转换为numba jitted函数内部的int - How can I cast a float numpy array value to an int inside of a numba jitted function in nopython mode Pandas astype int 不从值中删除小数点 - Pandas astype int not removing decimal points from values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM