【发布时间】:2020-06-21 17:48:25
【问题描述】:
我有一个数据框列,其中包含 nan 和整数的混合值。我的目标是检索第一个非 nan 值。该列看起来像这样 [nan, nan, 3, nan, 5, ...]。根据我在堆栈溢出中找到的答案,我想出了以下两种方法。显然,示例 1 的效率更高,但对于目标来说仍然感觉很复杂。有没有比下面的示例 no1 更好的方法来检索 pandas 系列的第一个非 nan 值?
# the column I want to access is the last in the df
df.iloc[df.col.first_valid_index(),-1]
每个循环 59.6 µs ± 2.54 µs(7 次运行的平均值 ± 标准偏差,每次 10000 个循环)
df.col.fillna(method='bfill')[0]
每个循环 208 µs ± 7 µs(7 次运行的平均值 ± 标准偏差,每次 1000 个循环)
【问题讨论】:
-
这是我的第一个问题:)
-
嗯...据我所知,并没有比 #1 好...而且您可能想要
loc- 而不是 iloc 用于您的索引恰好不在的地方零开始和 1 增量RangeIndex... 所以:df.loc[df['col'].first_valid_index()]...