python - Drop Upon Conditions -
i trying solve following problem: have dataframe. 1 of columns, have nan , numbers, distributed in random fashion. want drop lines based on column. criteria is: if line above 1 , 1 below have nan value, drop line. else, keep line in data frame.
this have managed to, quite sure wrong... appreciated!
i=0 while <= 500: if (np.isnan(df.iloc[i+1]['column1'])) & (np.isnan(df.iloc[i-1]['column1'])): df2[i] = df.drop(df[i])
create sample data:
np.random.seed(0) df= pd.dataframe({'column1': np.random.randn(10)}) df.iloc[[2, 4, 7], 0] = np.nan >>> df column1 0 1.764052 1 0.400157 2 nan 3 2.240893 # <<< drop. 4 nan 5 -0.977278 6 0.950088 7 nan 8 -0.103219 9 0.410599
apply filter.
>>> df[~((df['column1'].shift(1).isnull()) & (df['column1'].shift(-1).isnull()))] column1 0 1.764052 1 0.400157 2 nan 4 nan 5 -0.977278 6 0.950088 7 nan 8 -0.103219 9 0.410599
Comments
Post a Comment