[英]How to find the first 5 values (including nans) after first non nan value detected in pandas data frame row?
If I have a Pandas DataFrame like this:如果我有这样的 Pandas DataFrame:
0 1 2 3 4 5 6 7
A NaN NaN NaN 1 2 5 6 2
B NaN NaN NaN 2 NaN 1 NaN 3
C 5 4 3 2 1 5 9 1
D 6 2 NaN 5 1 3 5 NaN
E NaN NaN 6 2 1 3 5 1
How do I find the first five values after a non NaN value such that I get a Pandas data frame like this:如何在非 NaN 值之后找到前五个值,以便获得如下所示的 Pandas 数据框:
0 1 2 3 4
A 1 2 5 6 2
B 2 NaN 1 NaN 3
C 5 4 3 2 1
D 6 2 NaN 5 1
E 6 2 1 3 5
Here is one way using idxmax
and all
这是使用idxmax
和all
一种方法
df.loc[:,df.notnull().all().idxmax():]
3 4 5 6 7
A 1 2.0 5 6.0 2.0
B 2 NaN 1 NaN 3.0
C 2 1.0 5 9.0 1.0
D 5 1.0 3 5.0 NaN
E 2 1.0 3 5.0 1.0
Update更新
pd.DataFrame([df.iloc[i,x:].tolist() for i,x in enumerate(df.notnull().idxmax(1))]).iloc[:,:5]
0 1 2 3 4
0 1.0 2.0 5.0 6.0 2.0
1 2.0 NaN 1.0 NaN 3.0
2 5.0 4.0 3.0 2.0 1.0
3 6.0 2.0 NaN 5.0 1.0
4 6.0 2.0 1.0 3.0 5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.