假设我有以下pandas数据框:
userID dayID feature0 feature1 feature2 feature3
xy1 0 24 15.3 41 43
xy1 1 5 24 34 40
xy1 2 30 7 8 10
gh3 0 50 4 11 12
gh3 1 49 3 59 11
gh3 2 4 9 12 15
...
有许多用户标识,每个用户有3天,每天4个功能。 我要做的是针对每个功能,随机选择一天,然后削减矩阵。例如,如果功能部件0是第1天,功能部件1使用第0天,功能部件2使用第0天,功能部件3使用第2天:
^{pr2}$等等。在
我想出了:
我以为这段代码行得通,但实际上不行。
reduced_features = features.reset_index().groupby('userID').agg(lambda x: np.random.choice(x,1))
但这似乎很慢。有没有更快的方法?在
既然你得不到更多的建议,我就试一试:
检查以下代码示例(代码注释中的解释):
更多想法:
在运行apply(randx)之前,可以给出满足要求的随机行索引列表。例如,如果所有userID都具有相同数量的dayIDs,则可以使用一个列表列表来预置这些行索引。你也可以使用列表字典。在
提醒:如果您使用list of list和L.pop()生成行索引,请确保列表的数量至少应为number of unique userID+1,因为GroupBy.apply()在第一个组上调用其函数两次
而不是返回pd系列()在函数randx()中,可以直接返回一个列表(请参见函数randx()中带注释的return)。在这种情况下,所有检索到的特性将保存在一列中(见下文),您可以稍后对它们进行规范化。在
如果它仍然运行缓慢,可以将1000多个列(特性)分成组,即每次运行处理200个特性,相应地分割预定义的行索引,然后合并结果。
更新:在虚拟机(Debian-8,2GB RAM,1个CPU)上的示例测试下面:
但是,速度与使用agg的原始方法相似(np.随机选择()),但这个理论上是不正确的。你可能需要定义在你的期望中什么是慢的。在
有关randx_to_series()的更多测试:
希望这有帮助。在
环境:python3.6.4,Pandas 0.22.0
我承认,我对这个解决方案有点创意。在
我不认为你发布的代码和你在问题中解释的不一样。但是,这里有一段代码,它确实按用户标识随机分配每个特性的日期。在
输出:
^{pr2}$注意,这可能真的很慢,似乎一个新的解决方案可能会更快。在
在
相关问题 更多 >
编程相关推荐