Suppose I have a dataframe looking something like this:
col1 col2 col3 col4
0 A B F O
1 A G Q
2 A C G P
3 A H
4 A D I
5 A D I
6 A J U
7 A E J
How can I shift the columns if the column value is empty?
col1 col2 col3 col4
0 A B F O
1 A G Q
2 A C G P
3 A H
4 A D I
5 A D I
6 A J U
7 A E J
I thought I could check current column, if it's empty, take the next column value and make that empty.
for col in df.columns:
df[col] = np.where((df[col] == ''), df[f'col{int(col[-1])+1}'], df[col])
df[f'col{int(col[-1])+1}'] = np.where((df[col] == ''), '', df[col])
But I am failing somewhere. Sample df below.
df = pd.DataFrame(
{
'col1': ['A','A','A','A','A','A','A','A'],
'col2': ['B','','C','','D','D','','E'],
'col3': ['F','G','G','H','I','I','J',''],
'col4': ['O','Q','P','','','','U','J']
}
)