4. 串联DataFrame方法
# 使用isnull方法将每个值转变为布尔值
In[30]: movie = pd.read_csv('data/movie.csv')
movie.isnull().head()
Out[30]:
# 使用sum统计布尔值,返回的是Series
In[31]: movie.isnull().sum().head()
Out[31]: color 19
director_name 102
num_critic_for_reviews 49
duration 15
director_facebook_likes 102
dtype: int64
# 对这个Series再使用sum,返回整个DataFrame的缺失值的个数,返回值是个标量
In[32]: movie.isnull().sum().sum()
Out[32]: 2654
# 判断整个DataFrame有没有缺失值,方法是连着使用两个any
In[33]: movie.isnull().any().any()
Out[33]: True
原理
# isnull返回同样大小的DataFrame,但所有的值变为布尔值
In[34]: movie.isnull().get_dtype_counts()
Out[34]: bool 28
dtype: int64
更多
# movie数据集的对象数据包含缺失值。默认条件下,聚合方法min、max、sum,不会返回任何值。
In[35]: movie[['color', 'movie_title', 'color']].max()
Out[35]: Series([], dtype: float64)
# 要让pandas强行返回每列的值,必须填入缺失值。下面填入的是空字符串:
In[36]: movie.select_dtypes(['object']).fillna('').max()
Out[36]: color Color
director_name Étienne Faure
actor_2_name Zubaida Sahar
genres Western
...
movie_imdb_link [http://www.imdb.com/title/tt5574490/?ref_=fn_t...](http://www.imdb.com/title/tt5574490/?ref_=fn_t...)
language Zulu
country West Germany
content_rating X
Length: 12, dtype: object</pre>