【pandas】[7] Series 判斷每個元素是否爲空

有時候需要對Series中的每個元素進行判斷,然後做下一步邏輯處理

 

1、Series是數值類型的時候;裏面有空值(np.nan);value_counts()不會統計到空值。判斷時需要使用np.isnan(x)

ab = pd.Series([1, np.nan, 2])
ab
Out[55]: 
0    1.0
1    NaN
2    2.0
dtype: float64
ab.map(lambda x: np.isnan(x))
Out[56]: 
0    False
1     True
2    False
dtype: bool
ab.value_counts()
Out[57]: 
2.0    1
1.0    1
dtype: int64

 

2、Series是數值類型的時候;裏面有空值(np.nan);value_counts()不會統計到空值。判斷時需要使用x is np.nan

ab = pd.Series(['1', np.nan, '2'])
ab
Out[59]: 
0      1
1    NaN
2      2
dtype: object
ab.map(lambda x: x is np.nan)
Out[60]: 
0    False
1     True
2    False
dtype: bool
ab.value_counts()
Out[61]: 
2    1
1    1
dtype: int64

3、Series是數值類型的時候;裏面有空值(None);value_counts()不會統計到空值。判斷時需要使用np.isnan(x)

ab = pd.Series([1, None, 2])
ab
Out[67]: 
0    1.0
1    NaN
2    2.0
dtype: float64
ab.map(lambda x: np.isnan(x))
Out[69]: 
0    False
1     True
2    False
dtype: bool
ab.value_counts()
Out[70]: 
2.0    1
1.0    1
dtype: int64

4、Series是類別類型的時候;裏面有空值(None);value_counts()不會統計到空值。判斷時需要使用x is None

ab = pd.Series(['1', None, '2'])
ab
Out[63]: 
0       1
1    None
2       2
dtype: object
ab.map(lambda x: x is None)
Out[64]: 
0    False
1     True
2    False
dtype: bool
ab.value_counts()
Out[65]: 
2    1
1    1
dtype: int64

 

5、Series是類別類型的時候;裏面有空值('');value_counts()會統計到空值。判斷時需要使用x == ''

ab = pd.Series(['1', '', '2'])
ab
Out[77]: 
0    1
1     
2    2
dtype: object
ab.map(lambda x: x == '')
Out[78]: 
0    False
1     True
2    False
dtype: bool
ab.value_counts()
Out[79]: 
2    1
     1
1    1
dtype: int64

 

總結:

1、不管Series中存儲的是類別型還是數值型。如果裏面的空是np.nan或None。使用Series.value_counts()都不會將空統計進來;當裏面的空是''或' '。使用Series.value_counts(),會將空值統計進來

2、當Series中存儲的是數值型的時候,裏面的空是np.nan或None,統一使用np.isnan(x)進行判斷

3、當Series中存儲的是類別型的時候,裏面的空是np.nan的時候,使用x is np.nan判斷;裏面的空是None的時候,使用x is None判斷

4、不管Series中存儲的是類別型還是數值型。如果裏面的空是''或' '。使用x == '' 或 x.strip() == ''進行判斷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章