我有一个数据框:
2019-03-13 11:30:00+08:00 NaN NaN 0.001143
2019-03-13 15:00:00+08:00 NaN NaN NaN
2019-03-14 01:00:00+08:00 0.003653 NaN NaN
2019-03-14 10:15:00+08:00 NaN -0.002743 NaN
2019-03-14 11:30:00+08:00 NaN NaN 0.000229
2019-03-14 15:00:00+08:00 NaN NaN NaN
2019-03-15 01:00:00+08:00 -0.000229 NaN NaN
2019-03-15 10:15:00+08:00 NaN 0.003211 NaN
2019-03-15 11:30:00+08:00 NaN NaN -0.006192
2019-03-15 15:00:00+08:00 NaN NaN NaN
有没有一种方法可以获取每列的最新N = 2值而不会循环?也就是说,跳过所有的NaN
。存在一个last_valid_index()
,但是仅获取最后一个值。获得日期时间的重新索引数据框abset,以便它们对齐是很好的。这可能吗?
预期输出:
1 0.003653 -0.002743 0.000229
2 -0.000229 0.003211 -0.006192
答案 0 :(得分:3)
IIUC
df.apply(lambda x : sorted(x,key=pd.notnull)).iloc[-2:]
1 2 3
2019-03-15 0.003653 -0.002743 0.000229
2019-03-15 -0.000229 0.003211 -0.006192