[英]Pandas - find first non-null value in column
如果我有一個具有 NULL 或某些非空值的系列。 如何找到值不為 NULL 的第一行,以便我可以向用戶報告數據類型。 如果該值為非空,則該系列中的所有值都是相同的數據類型。
謝謝
您可以使用first_valid_index
和 select by loc
:
s = pd.Series([np.nan,2,np.nan])
print (s)
0 NaN
1 2.0
2 NaN
dtype: float64
print (s.first_valid_index())
1
print (s.loc[s.first_valid_index()])
2.0
# If your Series contains ALL NaNs, you'll need to check as follows:
s = pd.Series([np.nan, np.nan, np.nan])
idx = s.first_valid_index() # Will return None
first_valid_value = s.loc[idx] if idx is not None else None
print(first_valid_value)
None
對於一個系列,這將返回第一個非空值:
創建系列:
s = pd.Series(index=[2,4,5,6], data=[None, None, 2, None])
這創建了這個系列:
2 NaN
4 NaN
5 2.0
6 NaN
dtype: float64
您可以使用以下方法獲取第一個非 NaN 值:
s.loc[~s.isnull()].iloc[0]
返回
2.0
另一方面,如果您有這樣的數據框:
df = pd.DataFrame(index=[2,4,5,6], data=np.asarray([[None, None, 2, None], [1, None, 3, 4]]).transpose(),
columns=['a', 'b'])
看起來像這樣:
a b
2 None 1
4 None None
5 2 3
6 None 4
您可以使用此選擇每列的第一個非空值(對於 a 列):
df.a.loc[~df.a.isnull()].iloc[0]
或者,如果您希望第一行不包含 Null 值,則可以使用:
df.loc[~df.isnull().sum(1).astype(bool)].iloc[0]
返回:
a 2
b 3
Name: 5, dtype: object
您也可以使用get
方法代替
(Pdb) type(audio_col)
<class 'pandas.core.series.Series'>
(Pdb) audio_col.first_valid_index()
19
(Pdb) audio_col.get(first_audio_idx)
'first-not-nan-value.ogg'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.