简体   繁体   English

当时间序列中的一个值出现多次时替换它

[英]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.

相关问题 替换列表中的字符,即使它出现多次 - replacing a character in a list even when it appears more than once 如果值出现不止一次,则列出具有价值的列表 - Making list that takes in value if value appears more than once 解决列表项在文本中出现多次的算法错误 - solving algorithm bug when list item appears more than one time in text 如何在python中附加多个时间序列相关性列表? - how to append more than one list of time series correlation in python? Pandas - 向系列添加值,表示一个系列中的每个值在每年第一次出现 - Pandas - add value to series indicating the first time each value in one series appears in each year Python pandas:如果A列值出现多次,则分配B列的第一个值 - Python pandas: if column A value appears more than once, assign first value of column B 如何在 Pandas 数据框中选择值出现多次的行 - How to select rows in Pandas dataframe where value appears more than once 当同一个词出现多次时,在搜索文本中跟踪 position - Keeping track of position in searched text when the same word appears more than once 如何更改我的代码,以使 output 中的值仅显示一次,而不是使用随机数多次显示? - How can I change my code so that the value in the output only shows once instead of more than one time using random numbers? 在 Python 中,当该项目多次出现时替换字符串中的特定项目 - Replacing a specific item in a string when that item occurs more than once, in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM