2
votes

I have a data frame df:

   DT   RE   FE   SE C_Step
0  D1   E1   F1   S1   poor
1  D2   E3   F2  NaN    NaN
2  D1   E3  NaN   S2   good
3  D1  NaN   F1   S1   poor
4  D2  NaN   F1   S2   poor
5  D2   E3  NaN   S1   fair
6  D1   E3   F1   S2   fair
7  D2   E2   F1   S1    NaN

I want to retrieve df1 with no NAN values in first four columns of the data frame df and df2 with NAN values in first four columns of the data frame df.

Desired output:

df1 =

   DT   RE   FE   SE C_Step
0  D1   E1   F1   S1   poor
1  D1   E3   F1   S2   fair
2  D2   E2   F1   S1    NaN

df2 =

   DT   RE   FE   SE C_Step
0  D2   E3   F2  NaN    NaN
1  D1   E3  NaN   S2   good
2  D1  NaN   F1   S1   poor
3  D2  NaN   F1   S2   poor
4  D2   E3  NaN   S1   fair
2

2 Answers

2
votes

Using dropna

df1 = df.dropna(subset = ['DT','RE','FE','SE'])
df2 = df.loc[~df.index.isin(df.dropna(subset = ['DT','RE','FE','SE']).index)]

df1

    DT  RE  FE  SE  C_Step
0   D1  E1  F1  S1  poor
6   D1  E3  F1  S2  fair
7   D2  E2  F1  S1  NaN


df2

    DT  RE  FE  SE  C_Step
1   D2  E3  F2  NaN NaN
2   D1  E3  NaN S2  good
3   D1  NaN F1  S1  poor
4   D2  NaN F1  S2  poor
5   D2  E3  NaN S1  fair

Option 2: to find the rows with null

null_idx = df.index.difference(df.dropna(subset = ['DT','RE','FE','SE']).index)
df.iloc[null_idx]
1
votes

Create a mask with isnull + any:

m = df.iloc[:, 0:4].isnull().any(1)

df1 = df[~m]
#   DT  RE  FE  SE C_Step
#0  D1  E1  F1  S1   poor
#6  D1  E3  F1  S2   fair
#7  D2  E2  F1  S1    NaN

df2 = df[m]
#   DT   RE   FE   SE C_Step
#1  D2   E3   F2  NaN    NaN
#2  D1   E3  NaN   S2   good
#3  D1  NaN   F1   S1   poor
#4  D2  NaN   F1   S2   poor
#5  D2   E3  NaN   S1   fair