【发布时间】:2019-03-12 16:10:34
【问题描述】:
这是一个“ISO 第 53 周问题”。
我有一个 pandas Series 实例,其索引值代表 ISO 周数:
import pandas as pd
ts = pd.Series([1,1,1,2,3,1,2], index=[1,1,2,2,52,53,53])
我想用index = 52 或index = 1 随机且均等地替换所有index = 53 索引。
对于上述情况,这可能是:
import pandas as pd
ts = pd.Series([1,1,1,2,3,1,2], index=[1,1,2,2,52,52,1])
或
import pandas as pd
ts = pd.Series([1,1,1,2,3,1,2], index=[1,1,2,2,52,1,52])
例如。 请问我该怎么做?
感谢您的帮助。
编辑
在 numpy 中,我使用以下方法来实现:
from numpy import where
from numpy.random import shuffle
indices = where(timestamps == 53)[0]
number_of_indices = len(indices)
if number_of_indices == 0:
return # no iso week number 53 to fix.
shuffle(indices) # randomly shuffle the indices.
midway_index = number_of_indices // 2
timestamps[indices[midway_index:]] = 52 # precedence if only 1 timestamp.
timestamps[indices[: midway_index]] = 1
timestamps 数组是 pandas 的 index 值。
【问题讨论】:
-
你是说在每个值上添加
.6吗? -
@Chris 我重新格式化了问题。我认为只需随机更改索引值就足够了。
-
这里的“随机且均等”是什么意思?您想替换所有
53值,一半替换为1,一半替换为52,并随机分配?如果有奇数个53值怎么办? -
@KirkBroadhurst 请参阅编辑,了解我如何使用 numpy 实现这一目标。
标签: python pandas random series