Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to shift non nan values up and put nan values down

np.random.seed(100)
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
print (df)
          0         1         2         3
0 -1.749765       NaN  1.153036 -0.252436
1  0.981321  0.514219       NaN -1.070043
2       NaN       NaN -0.458027  0.435163
3 -0.583595  0.816847  0.672721 -0.104411
4 -0.531280  1.029733 -0.438136 -1.118318

df1 = df.apply(lambda x: pd.Series(x.dropna().values))
print (df1)
          0         1         2         3
0 -1.749765  0.514219  1.153036 -0.252436
1  0.981321  0.816847 -0.458027 -1.070043
2 -0.583595  1.029733  0.672721  0.435163
3 -0.531280       NaN -0.438136 -0.104411
4       NaN       NaN       NaN -1.118318
Comment

PREVIOUS NEXT
Code Example
Python :: looping over lists in python 
Python :: binary search tree in python 
Python :: tkinter radio button default selection 
Python :: while loop with if else 
Python :: delete content of table django 
Python :: swap two lists without using third variable python 
Python :: python recursion example 
Python :: python import list from py file 
Python :: django-oauth 
Python :: how to convert string into list in python 
Python :: pivot table but keep nan 
Python :: python tkinter 
Python :: python all but the last element 
Python :: assign exec function to variable python 
Python :: list slice in python 
Python :: get the last item in a python list 
Python :: docstring in python 
Python :: check if text is python 
Python :: python capture stdout 
Python :: atoi in python code 
Python :: timedelta format python 
Python :: sum of even numbers 
Python :: python dict delete key 
Python :: python increment by 1 
Python :: download button image streamlit 
Python :: python - input: integer 
Python :: delete multiple dataframes at once in python 
Python :: python map 
Python :: how to find the last element of list in python 
Python :: drop pandas 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =