#!/usr/bin/env python3 from pprint import pprint import numpy as np import pandas as pd A = [3,42,4,90,22,5,np.nan,np.nan,2,5,2,np.nan,23,61,32,24] B = [6,44,2,83,23,2,np.nan,np.nan,12,7,13,np.nan,np.nan,np.nan,43,2] C = [7,1,3,53,24,5,np.nan,np.nan,65,32,6,np.nan,23,63,12,34] D = [4,3,62,23,np.nan,34,np.nan,np.nan,1,7,12,np.nan,34,3,76,2] df = pd.DataFrame({ 'A':A, 'B':B, 'C':C, 'D':D }) pprint(df) # Output # A B C D # 0 3.0 6.0 7.0 4.0 # 1 42.0 44.0 1.0 3.0 # 2 4.0 2.0 3.0 62.0 # 3 90.0 83.0 53.0 23.0 # 4 22.0 23.0 24.0 NaN # 5 5.0 2.0 5.0 34.0 # 6 NaN NaN NaN NaN # 7 NaN NaN NaN NaN # 8 2.0 12.0 65.0 1.0 # 9 5.0 7.0 32.0 7.0 # 10 2.0 13.0 6.0 12.0 # 11 NaN NaN NaN NaN # 12 23.0 NaN 23.0 34.0 # 13 61.0 NaN 63.0 3.0 # 14 32.0 43.0 12.0 76.0 # 15 24.0 2.0 34.0 2.0 def fix_abc(row, column, df): # If the row/column value is null/nan if pd.isnull( row[column] ): # Get the value of row[column] from the row before prior = row.name value = df[prior-1:prior]['B'].values[0] # If that values empty, go to the row before that while pd.isnull( value ) and prior >= 1 : prior = prior - 1 value = df[prior-1:prior]['B'].values[0] else: value = row[column] return value df['A'] = df.apply( lambda x: fix_abc(x,'A',df), axis=1 ) df['B'] = df.apply( lambda x: fix_abc(x,'B',df), axis=1 ) df['C'] = df.apply( lambda x: fix_abc(x,'C',df), axis=1 ) def fix_d(x): if pd.isnull(x['D']): return 0 return x df['D'] = df.apply( lambda x: fix_d(x), axis=1 ) pprint(df) # A B C D # 0 3.0 6.0 7.0 3.0 # 1 42.0 44.0 1.0 42.0 # 2 4.0 2.0 3.0 4.0 # 3 90.0 83.0 53.0 90.0 # 4 22.0 23.0 24.0 0.0 # 5 5.0 2.0 5.0 5.0 # 6 2.0 2.0 2.0 0.0 # 7 2.0 2.0 2.0 0.0 # 8 2.0 12.0 65.0 2.0 # 9 5.0 7.0 32.0 5.0 # 10 2.0 13.0 6.0 2.0 # 11 13.0 13.0 13.0 0.0 # 12 23.0 13.0 23.0 23.0 # 13 61.0 13.0 63.0 61.0 # 14 32.0 43.0 12.0 32.0 # 15 24.0 2.0 34.0 24.0
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question