【问题标题】:Pandas: Randomly splitting index values between 2 index valuesPandas:在 2 个索引值之间随机拆分索引值
【发布时间】: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 = 52index = 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


【解决方案1】:

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

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

【讨论】:

  • 当然可以。因为您正在处理一个系列,所以列表理解应该很快。我做了一个 100 万行的快速测试,比300 ms
猜你喜欢
  • 2016-05-07
  • 2022-10-13
  • 2022-01-09
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2021-05-24
相关资源
最近更新 更多