当一个值出现不止一次时替换时间序列中的一个值

Replacing one value in a time series when it appears more than once

我正在尝试替换 python 系列中的一个值,这里的线索是我只想替换它一次,例如:

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])

数字2重复了3次,我只想把"second"2换成4, 我不想替换系列中的所有“2”号。

有什么办法吗?

提前致谢

您可以执行以下操作:

在我的代码中,min_pos 使您获得系列中 2 的第一个位置。 然后,我们使用 iloc 过滤第一次出现的位置,查找系列中 2 出现的下一个位置的索引。

import pandas as pd

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
min_pos = S[S==2].idxmin(2)
replace_idx = S.iloc[min_pos+1:].idxmin(2)
S.iloc[replace_idx] = 'new'

print(S)

输出

 0      0
1      1
2      2
3      3
4    new
5      5
6      2
7      6

你可以这样试试:

S.loc[((S == 2).cumsum() == 2).idxmax()] = 4
print(S)

输出:

0    0
1    1
2    2
3    3
4    4
5    5
6    2
7    6
dtype: int64

详情,找到Series中所有等于2的地方,然后用cumsum统计那些2,现在,select第一个出现的2的个数,用.loc设置值.