首页 > 解决方案 > Slicing Numpy ndarray

问题描述

I have used numpy to split a string at each ,. The output shows the split words. When I want to retrive first element, I get the following error:

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed.

Code

item = "3C2B,FF8BFF5F008C,64,2021-08-01T18:00:01Z,2a* "

item_value = np.char.split(item, sep = ',')

print(item_value)
> ['3C2B', 'FF8BFF5F008C', '64', '2021-08-01T18:00:01Z', '2a*']

print(type(item_value)) 
> <class 'numpy.ndarray'>

device_id = item_value[0]

Output:

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed.

Expected output: 3C2B

标签: pythonarraysnumpyindex-errornumpy-slicing

解决方案


使用np.str.split而不是np.char.split.

以下代码工作正常。

item = '3C2B,FF8BFF5F008C,64,2021-08-01T18:00:01Z,2a*'
item_value = np.str.split(item, sep = ',')
device_id = item_value[0]
print(device_id)

输出:

3C2B

推荐阅读