Reputation: 15
I have the following dataframe and wish to shift over the 0 values to the right and then revert each row:
H00 H01 H02 H03 H04 H05 H06
NR
1 33 28 98 97 0 0 0
2 29 24 22 98 97 0 0
3 78 76 98 97 0 0 0
4 16 15 98 97 0 0 0
5 81 72 70 98 97 0 0
This is the result I would like to get:
H00 H01 H02 H03 H04 H05 H06
NR
1 97 98 28 33 0 0 0
2 97 98 22 24 29 0 0
3 97 98 76 78 0 0 0
4 97 98 15 16 0 0 0
5 97 98 70 72 81 0 0
I've tried varius shift and apply combinations without any success. Is there a simple way of achieving this?
Upvotes: 1
Views: 138
Reputation: 5036
You can reverse the values that are greater than zero
def reverse_part(series):
series[series > 0] = series[series > 0][::-1]
return series
df.apply(reverse_part, axis=1, raw=True)
Out:
H00 H01 H02 H03 H04 H05 H06
NR
1 97 98 28 33 0 0 0
2 97 98 22 24 29 0 0
3 97 98 76 78 0 0 0
4 97 98 15 16 0 0 0
5 97 98 70 72 81 0 0
Upvotes: 3
Reputation: 42886
We can use the justify
function from this answer, then we use np.flip
to reverse your data over the horizontal axis:
a = df.to_numpy()
a = np.flip(justify(a, side='right'), axis=1)
df = pd.DataFrame(a, columns=df.columns)
H00 H01 H02 H03 H04 H05 H06
0 97 98 28 33 0 0 0
1 97 98 22 24 29 0 0
2 97 98 76 78 0 0 0
3 97 98 15 16 0 0 0
4 97 98 70 72 81 0 0
Upvotes: 3