I have a dataframe that looks like below
JavaScript
x
5
1
df = pd.DataFrame({'person_id': [101,101,101,101,202,202],
2
'person_type':['A','A','B','C','D','B'],
3
'course_id':[121,123,135,137,140,143],
4
'dep_id':[np.nan,Z12,np.nan,B12,np.nan,D12})
5
I would like to position shift by 1 cell to the right if there is NA
in the column dep_id
.
I tried the below but it wasn’t working
JavaScript
1
4
1
l = list(np.arange(0,len(df.columns) -1))
2
np.where(df['dep_id'].isna(), l.insert(0,-1))
3
df.iloc[:,l]
4
Any efficient and elegant approach to shift column position on big data?
For example, I expect my output to be like as shown below
Advertisement
Answer
Let us try shift
along axis=1
JavaScript
1
3
1
m = df['dep_id'].isna()
2
df.loc[m, :] = df[m].shift(axis=1)
3
JavaScript
1
8
1
person_id person_type course_id dep_id
2
0 NaN 101 A 121
3
1 101.0 A 123 Z12
4
2 NaN 101 B 135
5
3 101.0 C 137 B12
6
4 NaN 202 D 140
7
5 202.0 B 143 D12
8