2016-08-23 58 views
2

这似乎是简单的数据处理操作。但我坚持这一点。熊猫/ Python中的数据处理

我有一个活动的推荐数据集。

Masteruserid content 

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

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

global_content 
100 
300 
301 
101 

实际上我有4000+的Masteruserid's。现在我需要帮助,以便如何开始接近这一点。

+0

也正是预期的输出或你的问题/问题?听起来就像你想从“全局”中选择任何2个元素,而不是在“活动”的内容中......听起来对于SQL语句非常熟悉 –

+0

是的,我想为每个masteruserid 5个元素。所以任何缺失的元素都从全球范围内挑选出来。我想在python中做到这一点。 – user2906657

+0

据我所知,SQL可以很好地转换成Dataframes逻辑。你应该[编辑]你的问题,包括一些尝试解决问题。 –

回答

1
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

0

试试这个,用这个作为区域经济共同体列表,

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]