Pandas/Python中的数据操作

2024-10-01 02:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这似乎是一个简单的数据操作。但我被困在这里。你知道吗

我有一个竞选活动的推荐数据集。你知道吗

Masteruserid content 

1             100
1             101
1             102
2             100
2             101
2             110

现在我们要为每个用户推荐至少5个内容。例如,masteruserid1有三个建议,我想从全局查看的内容中随机选取其余两个,这是一个单独的数据集(列表)。然后,我还必须检查重复的情况下,如果随机挑选已经存在于原始数据集。你知道吗

global_content
100
300
301
101

实际上,我有大约4000多个Masteruserid的。现在我需要帮助,就如何开始接近这个。你知道吗


Tags: 数据用户内容列表原始数据情况content全局
2条回答

试试这个,用这个作为记录列表

df2['global_content']

0    100
1    300
2    301
3    101
4    400
5    500
6    401
7    501

recs = pd.DataFrame()
recs['content'] = df.groupby('Masteruserid')['content'].apply(lambda x: list(x) + np.random.choice(df2[~df2.isin(list(x))].dropna().values.flatten(), 2, replace=False).tolist())
recs

                                    content
Masteruserid                               
1             [100, 101, 102, 300.0, 301.0]
2             [100, 101, 110, 501.0, 301.0]
def add_content(df, gc, k=5):
    n = len(df)
    gcs = set(gc.squeeze())
    if n < k:
        choices = list(gcs.difference(df.content))
        mc = np.random.choice(choices, k - n, replace=False)
        ids = np.repeat(df.Masteruserid.iloc[-1], k - n)
        data = dict(Masteruserid=ids, content=mc)

        return df.append(pd.DataFrame(data), ignore_index=True)


gb = df.groupby('Masteruserid', group_keys=False)
gb.apply(add_content, gc).reset_index(drop=True)

enter image description here

相关问题 更多 >