在上一篇文章中,我要求使用 Python 中的字典从数据帧构建序列。
Construct sequences from a dataframe using dictionaries in Python
我想将所选答案中提出的函数更改为仅包含列表中没有日期的项目。
拥有:
{1: [1, 2], 2: [3, 1,], 4: [5, 3, 1]}
而不是:
{1: [[1, 'date_1'], [2, 'date_2']],
2: [[3, 'date_1'], [1, 'date_3']],
4: [[5, 'date_2'], [3, 'date_3'], [1, 'date_5']]}
更改功能:
fnc = lambda x: x.sort_values('date').values.tolist()
df.set_index('users').groupby(level=0).apply(fnc).to_dict()
最佳答案
当在整个 df 上调用 lambda 时,您可以只选择 lambda 中的项目列,您可以从结果中进行子选择,以便只获得结果中感兴趣的列:
In [249]:
fnc = lambda x: x.sort_values('date')['items'].values.tolist()
df.set_index('users').groupby(level=0).apply(fnc).to_dict()
Out[249]:
{1: [1, 2], 2: [3, 1], 4: [5, 3, 1]}
关于 python : extracting only the first element on a dictionary of list using functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747145/