[英]Replacing one value in a time series when it appears more than once
I am trying to replace a value in a python Series, the clue here is that I want to replace it only once, for instance:我正在尝试替换 python 系列中的一个值,这里的线索是我只想替换它一次,例如:
S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
The number 2 is repeated 3 times and I want to replace only the "second" 2 for 4, I don't want to replace all the '2' numbers within the series.数字 2 重复了 3 次,我只想将“第二个”2 替换为 4,我不想替换系列中的所有“2”数字。
Is there any way to do it?有什么办法吗?
Thank you in advance先感谢您
You can do the following:您可以执行以下操作:
In my code min_pos
gets you the first position where 2 is in the Series.在我的代码min_pos
,您将获得系列中 2 的第一个位置。 We then look for the index of the next position where 2 appears in the Series using iloc
to filter the first occurrence.然后,我们使用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)
Output输出
0 0
1 1
2 2
3 3
4 new
5 5
6 2
7 6
You can try this way:你可以试试这个方法:
S.loc[((S == 2).cumsum() == 2).idxmax()] = 4
print(S)
Output:输出:
0 0
1 1
2 2
3 3
4 4
5 5
6 2
7 6
dtype: int64
Details, find all the places in the Series where equal to 2, then use cumsum to count those 2's, now, select the first occurrence of the count of 2 and use .loc to set the value.详细信息,找到系列中所有等于 2 的位置,然后使用 cumsum 计算那些 2,现在,选择 2 的计数的第一次出现并使用 .loc 设置值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.