【问题标题】:Sort to get the list of elements in first place , list of ones in 2nd place etc排序以获取第一名的元素列表,第二名的元素列表等
【发布时间】:2021-09-06 17:33:06
【问题描述】:

有一个小数据框(groupby 中的一个组,但与这个问题并不真正相关),排序后看起来像这样:

df = pd.DataFrame([['a', 'b', 'c'], [1,2,2], [1,3,3]]).T
df.columns = ['name', 'sorter1', 'sorter2']
sorted_df = df.sort_values(['sorter1', 'sorter2'])
name sorter1 sorter2
0 a 1 1
1 b 2 3
2 c 2 3

想要将其转移到第一、第二和第三位的数据框中, 明白了:

result = sorted_df[['name']].T
result.columns = ['first', 'second', 'third']
first second third
name a b c

但我真正需要的是:

first second third
name a ['b', 'c'] nan

欢迎任何想法,熊猫或其他,谢谢。

【问题讨论】:

    标签: python pandas sorting


    【解决方案1】:

    一种方式:

    df.sort_values(['sorter1', 'sorter2'], inplace=True)
    df = df.groupby(['sorter1', 'sorter2'], as_index=False, sort=False).agg(list).reindex(df.index)[['name']].T
    

    【讨论】:

    • 工作正常,但缺少排序,可以在 groupby 之前添加排序,并通过向其添加 sort=False 标志强制 groupby 不使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2019-04-19
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多