VisibleDeprecationWarning:一个关于List创建ndarray的警告
Warning的出现
本人在白嫖数据分析课程时,老师在课堂上出现的一个迷惑性报错。可惜的是老师在课堂上并未找出和说明原因,只是单方面的删除了对一个方法的使用。
# 导入第三方库
import pandas as pd
import numpy as np
# 文件路径
file_path='./archive_03/IMDB-Movie-Data.csv'
#pandas读取csv文件
movie = pd.read_csv(file_path)
# 目的:获取演员的人数
temp_actors_list = movie['Actors'].str.split(',').tolist()
# 这里是DataFrame中的演员并做切割处理,转话为列表
actors_list = list(np.array(temp_actors_list).flatten())
# 由于temp_actors_list为列表里面还有一个列表的形式,
# 这里通过np.array()转为数组形式并且flatten展开为一维数组
actors_num = len(set(actors_list)) #set()转为集合去重,最后len()查列表长度
print(actors_num) #打印结果
想法固然美好,但出现了Warning
:
Warning
的出现,只是删除方法去解决,不能使我满足。我更想知道为什么会出现Warning
?如何避免再出现Warning
?
为什么会出现Warning?
首先,我们先通过百度翻译,翻译以下Warning
:
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. actors_list = list(np.array(temp_actors_list).flatten())
得到中文:
到这里,我们已经可以了解大概的原因了,似乎是我们在创建ndarray
时,没有使用相同长度的列表造成Warning
,最后导致了后面TypeError
.
接下来,我们进行基本的debug
操作:
1.查看以下代码:
actors_list = list(np.array(temp_actors_list).flatten())
创建ndarray
,我们这里使用的是np.array(temp_actors_list)
。也就是说,temp_actors_list里面的列表长度并不统一?!
2.使用print()
寻找证据
print(temp_actors_list