VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
(which is a list-or-tuple of lists-or-tuples-or ndarrays with different
lengths or shapes) is deprecated. If you meant to do this, you must specify ‘dtype=object’
when creating the ndarray. newArr = np.array(list_A)

原因
list里添加数组元素时没有正确索引,导致append加入的是array,后续将list通过np.array进行转换时出现警告

解决方法
x = B[0][i]后添加[0]

也可能存在的原因:列表不规则,长短不一,在np.array(list_A)之前检查list_A

Code

import numpy as np

print(numpy.__version__) # 1.22.2
A = np.arange(1, 25).reshape(4, 6)

list_A = A.flatten().tolist()

B = np.array([[[0, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.int32)
print(A)
print(list_A)
"""
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences 
(which is a list-or-tuple of lists-or-tuples-or ndarrays with different 
lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object'
 when creating the ndarray. newArr = np.array(list_A)
"""
for i in range(B.shape[1]):
    x = B[0][i]# type(x) :   DeprecationWarning
    # x = B[0][i][0]# solve type(x) : 
    # print(type(x))
    list_A.append(x)

print(list_A)
newArr = np.array(list_A)
print(newArr)

你可能感兴趣的:(python)