如何在Python中将0和1的数组转换为字符串数组?

2024-04-26 02:41:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python数组:np.array([1,1,1,0,0]),我想根据条件if 1, 'yes', else 'no'将其转换为以下数组:np.array(['yes','yes','yes','no','no])。最好的办法是什么?我很乐意在原地或单独的阵列中进行。你知道吗


Tags: noifnp数组条件arrayelseyes
2条回答

使用np.where

import numpy as np

arr = np.array([1,1,1,0,0])

result = np.where(arr, 'yes', 'no')
print(result)

输出

['yes' 'yes' 'yes' 'no' 'no']

您可以使用列表理解:

import numpy as np

arr = np.array([1,1,1,0,0])

result = np.array(['yes' if x else 'no' for x in arr])

print(result)

输出:['yes' 'yes' 'yes' 'no' 'no']

相关问题 更多 >