【问题标题】:How to group by hierarchical data in pandas/sql?如何在 pandas/sql 中按分层数据分组?
【发布时间】:2019-09-20 19:17:01
【问题描述】:

我在层次结构上有问题。我有这样的数据。

   id       performance_rating     parent_id     level
   111           8                   null         0 
   122           3                   null         0
   123           9                   null         0
   254           5                   111          1
   265           8                   111          1
   298           7                   122          1
   220           6                   123          1
   305           5                   298          2
   395           8                   220          2
   ...           ...                 ...         ...
   654           4                   562          5

id 是人的唯一身份。 performance_rating 是他的评分,满分 10 parent_id 是在相应id之上工作的人的id。

我需要找出一棵树的平均评分 (111,122,123)。

我尝试的是根据级别单独的数据框。然后合并它和groupby。但是很长。

【问题讨论】:

  • roll up 是什么意思?
  • 该id下所有孩子的平均值

标签: python sql pandas postgresql group-by


【解决方案1】:

会有几种不同的方法来做到这一点 - 这是一个丑陋的解决方案。

我们在函数上使用 while 和 for 循环来“回溯”数据帧的每一列: 这要求我们首先将 'id' 设置为索引并按 'level' 降序排序。它也不需要重复的 ID。如下:

df = df.set_index('id')
df = df.sort_values(by='level', ascending=False)

for i in df.index:
    while df.loc[i, 'level'] > 1:
        old_pid = df.loc[i, 'parent_id']
        df.loc[i, 'parent_id'] = df.loc[old_pid, 'parent_id']
        old_level = df.loc[i,'level']
        df.loc[i, 'level'] = old_level - 1

这样,无论有多少级别,我们都将所有内容都留在层次结构的第 1 级,然后可以这样做:

grouped = df.groupby('parent_id').mean()

(或您需要的任何变体) 希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 2019-04-15
    • 2020-12-15
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2014-09-05
    相关资源
    最近更新 更多