熊猫:在 2 个索引值之间随机拆分索引值



这是一个"ISO 第 53 周问题"。

我有一个熊猫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 = 53索引替换为index = 52index = 1.

对于上述情况,这可能是:

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数组是熊猫index值。

如果我正确理解你,列表理解应该可以工作:

ts = pd.Series([1,1,1,2,3,1,2], index=[1,1,2,2,52,53,53])
ts.index = [i if i != 53 else np.random.choice([1,52]) for i in ts.index]
1     1
1     1
2     1
2     2
52    3
52    1
1     2
dtype: int64

最新更新