python - Pandas:在 2 个索引值之间随机拆分索引值
问题描述
这是一个“ISO 第 53 周问题”。
我有一个 pandasSeries
实例,其索引值代表 ISO 周数:
import pandas as pd
ts = pd.Series([1,1,1,2,3,1,2], index=[1,1,2,2,52,53,53])
我想用or随机且平等地替换所有index = 53
索引。index = 52
index = 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
推荐阅读
- networking - 在浏览器或 wget 命令中访问 gitlab 服务器 url 时出现错误 ERR_EMPTY_RESPONSE
- javascript - 过滤来自登录请求的响应以删除标头和配置数据
- sql-server - 在 Visual Studio 的数据源中键入地址
- javascript - 重新运行 const 声明的函数的最佳方法是什么?
- wordpress - 无法为 Wordpress 设置联系表格 7 的样式
- r - R中表格值之间的3D插值
- react-native - 如何修复“RealmObject 不能作为函数调用”realm-js 错误?
- javascript - Javascript 错误:.split 不是函数
- database - 更新单个模式的序列不起作用(Postgres 12)
- html - Django HTML在提交时将POST数据作为PK值发送到url