首页 > 解决方案 > 创建熊猫列表子序列的有效方法

问题描述

所以我有一个看起来像这样的数据框:

    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 方法。是否有任何熊猫方法可以帮助更有效地做到这一点?

标签: pythonpandasdata-structuresdata-science

解决方案


一个解决方案可能是首先调用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])

最终结果

在此处输入图像描述


推荐阅读