按列分组并获取组中行的字典列表。

huangapple go评论74阅读模式
英文:

Group by a column and get a list of dict of rows in the group

问题

在一个类似这样的数据框中:

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6

我想要按照 col1 进行分组,并且从另外两列中获取一个字典列表,结果如下:

   col1  rows_group  
0     1  [{"col_2": 3, "col_3": 5}, {"col_2": 3, "col_3": 6}]
1     2  [{"col_2": 4, "col_3": 5}, {"col_2": 4, "col_3": 6}]

我该如何实现这个目标?

英文:

in a dataframe like this:

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6

I want to group by col1 and get a list of dict's from the other two coluns like this:

   col1  rows_group  
0     1  [{"col_2": 3, "col_3": 5}, {"col_2": 3, "col_3": 6}]
1     2  [{"col_2": 4, "col_3": 5}, {"col_2": 4, "col_3": 6}]

how can i achieve this?

答案1

得分: 2

我终于找到了如何使用 groupby.applyto_dict 来实现这个目标的方法:

df.groupby('col1').apply(
    lambda x: x[['col2', 'col3']].to_dict('records')
).reset_index(name='rows_group')

或者:

(df.set_index('col1').groupby(level=0)
   .apply(lambda g: g.to_dict('records'))
   .reset_index(name='rows_group')
)

输出结果:

   col1                                        rows_group
0     1  [{'col2': 3, 'col3': 5}, {'col2': 3, 'col3': 6}]
1     2  [{'col2': 4, 'col3': 5}, {'col2': 4, 'col3': 6}]
英文:

I finally found how to achieve this with groupby.apply and to_dict:

df.groupby('col1').apply(
    lambda x: x[['col2', 'col3']].to_dict('records')
).reset_index(name='rows_group')

Alternatively:

(df.set_index('col1').groupby(level=0)
   .apply(lambda g: g.to_dict('records'))
   .reset_index(name='rows_group')
)

Output:

   col1                                        rows_group
0     1  [{'col2': 3, 'col3': 5}, {'col2': 3, 'col3': 6}]
1     2  [{'col2': 4, 'col3': 5}, {'col2': 4, 'col3': 6}]

huangapple
  • 本文由 发表于 2023年6月16日 05:27:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定