python - 创建熊猫列表子序列的有效方法
问题描述
所以我有一个看起来像这样的数据框:
user_id movie_embedding_index
0 6 [998.0, 520.0, 755.0, 684.0, 13.0, 4248.0, 1.0...
1 7 [1216.0, 12.0, 148.0, 1.0, 289.0, 64.0, 110.0,...
2 8 [40.0, 199.0, 42.0, 316.0, 96.0, 34.0, 152.0, ...
3 10 [117.0, 2283.0, 1.0, 25.0, 29.0, 14.0, 11.0, 2...
4 25 [5263.0, 117.0, 5003.0, 5086.0, 34.0, 152.0, 1...
每个 user_id 都有电影历史,[998.0, 520.0, 755.0, 684.0, 13.0, 4248.0]
我想为这个用户历史创建多个序列,封装过去的历史和观看的下一部电影。因此,对于历史,[998.0, 520.0, 755.0, 684.0, 13.0, 4248.0]
我想创建以下序列:
past_history next_movie
[] 998.0
[998.0] 520.0
[998.0,520.0] 755.0
...
[998.0, 520.0, 755.0, 684.0, 13.0] 4248.0
我想为数据框中的所有用户构建它并获得最终结果,例如:
user_id past_history next_movie
0 6 [] 998.0
1 6 [998.0] 520.0
2 6 [998.0,520.0] 755.0
.
.
.
我可以想到这样做的方法,但是它们效率极低,并且不使用 pandas 方法。是否有任何熊猫方法可以帮助更有效地做到这一点?
解决方案
一个解决方案可能是首先调用apply
您想要的计算。
import pandas as pd
# Generate an example dataframe
d = {'user_id': [1, 2, 3], 'movie_embedding_index': [[998.0, 520.0, 755.0, 684.0, 13.0, 4248.0], [98.0, 20.0, 55.0, 84.0], [132.0, 5432.0, 97-0, 675.0]]}
df = pd.DataFrame(data=d)
# Calculate lists of past movies and current movie
df['calculation'] = df.movie_embedding_index.apply(lambda x: [(x[:index], elem) for index, elem in enumerate(x, start=0)])
然后应用于explode
此计算列
df = df.explode('calculation')
最后将这些值检索为新列
df['past_history'] = df['calculation'].apply(lambda x: x[0])
df['next_movie'] = df['calculation'].apply(lambda x: x[1])
最终结果:
推荐阅读
- c - 根据文本文件计算字符、单词和行数
- python - 如何从字典创建 MultiIndex 列
- r - 分组内的ggplot百分比
- typescript - 打包电子应用程序后无法 mkdir 获取日志文件
- python - 如何让 python-chess SVG 渲染在 Google Colab 中工作?
- python - Python 不会多次迭代循环
- r - 使用 purrr 标记许多模型的回归样本
- javascript - 使用 PHP 和 Ajax 从 MySQL 检索数据到动态输入
- python - 由于文件夹名称,python 中的 AWS lambda 函数失去了依赖关系
- python - django.db.utils.IntegrityError:关系“shop_book”的“genre_id”列中的空值违反非空约束