我有以下数据框架:
data1 = [[2,5,6,3,1],
[2,2,5,4,2],
[0,1,2,2,3],
[6,2,1,0,9],
[2,3,4,1,2]]
df = pd.DataFrame(data1)
print(df)
I need to replace only the last occurrence of the value 2 in each column with the value 7. Note the replacement is ONLY for the last 2 , the proceeding 2 s in the column should remain in place. The desired result being:
[[2,5,6,3,1],
[2,2,5,4,2],
[0,1,7,7,3],
[6,7,1,0,9],
[7,3,4,1,7]]
I tried to use last_valid_index()
, as well as diff()
, and did not get the results I was looking for.
Like the following:
cond = df.eq(2) & df.last_valid_index()==2
out = df.mask(cond, 7)
print(out)
我已尝试过这些版本以及<编码>diff(>>),我似乎无法取得预期结果(如上所示)。 任何建议都将受到高度赞赏。