Issue
I have a DataFrame like this:
col1 | col2 | col3 | col4 |
---|---|---|---|
5 | 7 | 12 | 9 |
0 | 9 | 9 | 1 |
9 | 9 | 1 | 1 |
10 | 5 | 2 | 9 |
9 | 3 | 0 | 18 |
Each row has at least one 9 and for each row, I want to replace the first instance of it with 90.
Currently, I'm doing:
out = df.mask(df.eq(9) & df.apply(lambda x: ~x.duplicated(), axis=1), 90)
Is there any better/faster way than this?
Expected output:
col1 col2 col3 col4
0 5 7 12 90
1 0 90 9 1
2 90 9 1 1
3 10 5 2 90
4 90 3 0 18
Constructor:
data = {'col1': [5, 0, 9, 10, 9],
'col2': [7, 9, 9, 5, 3],
'col3': [12, 9, 1, 2, 0],
'col4': [9, 1, 1, 9, 18]}
df = pd.DataFrame(data)
Solution
You may check with numpy
assign
df.values[df.index, np.argmax(df.values==9,1)] = 90
df
Out[56]:
col1 col2 col3 col4
0 5 7 12 90
1 0 90 9 1
2 90 9 1 1
3 10 5 2 90
4 90 3 0 18
Answered By - BENY
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.