【问题标题】:Pandas - find first non-null value in columnPandas - 在列中找到第一个非空值
【发布时间】:2017-06-27 12:16:46
【问题描述】:

如果我有一个具有 NULL 或一些非空值的系列。如何找到值不为 NULL 的第一行,以便将数据类型报告给用户。如果该值为非 null,则该系列中的所有值都是相同的数据类型。

谢谢

【问题讨论】:

标签: python pandas


【解决方案1】:

你也可以改用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'

【讨论】:

    【解决方案2】:

    您可以将first_valid_indexloc 的选择一起使用:

    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.loc[idx] 实际上会返回一个系列。 @jezrael 你认为有一个很好的通用解决方案在这种情况下也可以工作,还是以first_valid_value 的类型为条件是不可避免的?
    • @Stav - 不容易的问题,也许是最好的新问题。
    【解决方案3】:

    对于一个系列,这将返回第一个非空值:

    创建系列:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多