Skip to main content
 首页 » 编程设计

python之Pandas/Python 中的数据操作

2025年04月02日14xing901022

看似简单的数据操作操作。但我坚持这一点。

我有一个事件的推荐数据集。

Masteruserid content  
 
1             100 
1             101 
1             102 
2             100 
2             101 
2             110 

现在我们要为每个用户推荐至少 5 个内容。因此,例如 Masteruserid 1 有三个建议,我想从全局查看的内容中随机选择剩下的两个,这是一个单独的数据集(列表)。然后我还必须检查重复项,以防原始数据集中已经存在随机选择的数据。

global_content 
100 
300 
301 
101 

实际上我有大约 4000 多个 Masteruserid。现在,我需要有关如何着手解决这个问题的帮助。

请您参考如下方法:

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)