Left shift with condition in pandas

Viewed 70

I have some problems with a csv file, I have tried several solutions through the pandas library but none has worked for me, I want to make a left shift to 3 columns in case that in one of them appears a certain code (in this case 11 or 22), for example, this would be my input:

code name % code 2 name 2 % 2 code 3 name 3 % 3
11 John 34 44 Rob 23 33 Peter 15
22 Ken 45 33 Peter 45 44 Rob 25
33 Peter 34 66 Abraham 37 77 Harry 67
11 John 45 77 Harry 39 88 Mary 20

And I expect something like this:

code name % code 2 name 2 % 2 code 3 name 3 % 3
44 Rob 23 33 Peter 15
33 Peter 45 44 Rob 25
33 Peter 34 66 Abraham 37 77 Harry 67
77 Harry 39 88 Mary 20

any idea how I could solve my problem with pandas?

Thanks in advance!

1 Answers

Do you want this?

mask = df['code'].isin([11,22])
df.loc[mask] = df.loc[mask].shift(-3,axis=1)

Output -

  code   name     %  code 2   name 2   % 2  code 3 name 3   % 3
0  44.0    Rob  23.0    33.0    Peter  15.0     NaN    NaN   NaN
1  33.0  Peter  45.0    44.0      Rob  25.0     NaN    NaN   NaN
2  33.0  Peter  34.0    66.0  Abraham  37.0    77.0  Harry  67.0
3  77.0  Harry  39.0    88.0     Mary  20.0     NaN    NaN   NaN
Related