I want to extract n consecutive cells (without taking into account the non values) from a dataframe like the following:
We can have the following dataframes for n=2:
or
CodePudding user response:
Consider
>>> df
0 1 2 3
0 0.0 1.0 NaN 23
1 NaN 1.0 23.0 4
2 NaN NaN 1.0 0
3 0.0 NaN NaN 1
>>> df.apply(lambda s: s.dropna().iloc[:2].reset_index(drop=True), axis=1)
0 1
0 0.0 1.0
1 1.0 23.0
2 1.0 0.0
3 0.0 1.0
edit: this will give you the first two (or n) non missing values from each row. Your question is unclear on whether this is sufficient.



