python boolean numpy array_使用Numpy布尔数组的索引Python列表 (Index Python List with Numpy Boolean Array)...

本文介绍了如何利用Numpy的布尔数组来索引Python列表,建议直接使用Numpy数组以提高代码可读性。通过示例展示了如何创建和操作包含字符串的Numpy数组,包括赋值和筛选操作。需要注意的是,数组元素长度必须小于指定的dtype长度,否则超出部分会被截断。
摘要由CSDN通过智能技术生成

Do you need it to be a list. Since you want to use the indexing behavior of a numpy array, it would make better sense to other people that read your code if you actually use a numpy array.

Maybe try using an array with dtype='a'? For example in the code below,

x = sp.array(['a', 'b', 'c'], dtype='a')

print(x)

print(x=='c')

print(x[x=='c']).

This will return the following arrays,

['a' 'b' 'c']

[False False True]

['c'].

Assignment will work as you would expect too,

x[x=='c'] = 'z'

print(x).

This will return the modified array,

['a' 'b' 'z'].

The only concern is that the elements of the array cannot be longer than the allocated length. Here it is specified as one with dtype='a'. You can use dtype='a5' or dtype='aN' for any length you want. All the elements of the array must be strings that are shorter than the maximum length.

If you pass a string that is too long it will chop off the end, as in the following example with dtype set to 'a2':

x = sp.array(['abc', 'bcd', 'cde'], dtype='a2')

print(x),

which gives,

['ab' 'bc' 'cd'].

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值