我有一个pandas数据框,如下所示,我需要每周提取所有唯一用户ID: -
sender_user_id created
0 2 2016-12-19 03:34:30.013923
1 3 2016-12-20 03:34:30.013923
2 6 2016-12-21 03:34:30.013923
3 22 2016-12-22 03:34:30.013923
3 6 2016-12-22 06:34:30.013923
我需要一个输出字典或数据框,它每周聚合所有唯一的user_id,看起来像这样
created user_ids
0 2016-12-19 03:34:30.013923 2,5,24,15,6
1 2016-12-25 03:34:30.013923 8,9,14,21,5
我知道我们可以每周拆分数据帧并使用
numpy.unique()函数,但是有一个很好的优化方法吗?
答案 0 :(得分:1)
考虑这个随机生成的df
rng = np.arange(100)
df = pd.DataFrame(columns=['sender_user_id', 'created'])
for t in pd.date_range('2016-03-31', periods=10, freq='3B'):
for i in np.random.permutation(rng)[:5]:
df = df.append(dict(sender_user_id=i, created=t), ignore_index=True)
df.sender_user_id = df.sender_user_id.astype(int)
resample
on
df.resample('W', on='created').sender_user_id.unique().reset_index(name='user_ids')
答案 1 :(得分:0)
试试这个:
def aggregate_function (df, col_1, col_2):
new_df = pd.DataFrame([], columns=[col_1, col_2])
new_df[col_1] = sorted (set (df[col_1]))
new_df[col_2] = new_df[col_1].map(lambda x: sorted (set (df.loc[df[col_1]==x, col_2])))
return (new_df)
>>> aggregate_function (df, 'created', 'user_ids')
>>> created user_ids
0 2016-12-19 03:34:30.013923 2,5,24,15,6
1 2016-12-25 03:34:30.013923 8,9,14,21,5