加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-熊猫:在两个索引值之间随机分割索引值

发布时间:2020-12-17 17:39:32 所属栏目:Python 来源:网络整理
导读:这是“ ISO第53周的问题”. 我有一个pandas Series实例,其索引值表示ISO周编号: import pandas as pdts = pd.Series([1,1,2,3,2],index=[1,52,53,53]) 我想将所有index = 53索引随机且均等地替换为index = 52或index = 1. 对于上述情况,可能是: import pan

这是“ ISO第53周的问题”.

我有一个pandas Series实例,其索引值表示ISO周编号:

import pandas as pd
ts = pd.Series([1,1,2,3,2],index=[1,52,53,53])

我想将所有index = 53索引随机且均等地替换为index = 52或index = 1.

对于上述情况,可能是:

import pandas as pd
ts = pd.Series([1,1])

要么

import pandas as pd
ts = pd.Series([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数组是熊猫索引值.

最佳答案
如果我对您的理解正确,则列表理解应该可以:

ts = pd.Series([1,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读