【问题标题】:How to group items then iterate through subgroups [duplicate]如何对项目进行分组然后遍历子组[重复]
【发布时间】:2019-06-08 21:54:18
【问题描述】:

假设我有一个如下所示的数据框:

    interview       longitude        latitude
1   A1                  34.2             90.2
2   A1                  54.2             23.5
3   A3                  32.1             21.5
4   A4                  54.3             93.1
5   A2                  45.1             29.5
6   A1                  NaN              NaN
7   A7                  NaN              NaN
8   A1                  NaN              NaN
9   A3                  23.1             38.2
10  A5                  -23.7            -98.4

我希望能够执行某种 groupby 方法,输出每个子组及其各自的经度和纬度。因此,类似这样的期望输出将是:

    interview         longitude         latitude 
1   A1                  34.2             90.2
2   A1                  54.2             23.5
6   A1                  NaN              NaN
8   A1                  NaN              NaN

5   A2                  45.1             29.5

3   A3                  32.1             21.5
9   A3                  23.1             38.2

... and so on

所以这需要循环完成,因为我需要遍历每个子组的每一行。

我的目标是为每个面试(A1、A2、...)找出哪个面试官(A1、A2、...)走的距离最长 - 本质上,我只需要能够执行一些每个子组内的计算.. 我将如何迭代地执行这种分组方法,以便我可以再次迭代地在每个子组内执行操作,

谢谢!

【问题讨论】:

  • 根据您的输出,这看起来不像 groupby,这看起来像 df.sort_values(by=['interview','longitude','latitude'], ascending=False)。对于您描述的用例,添加一个计算距离的列更有意义(我假设从/到一些常见的经纬度?)然后执行df.groupby('interview').max()['distance']

标签: python pandas dataframe pandas-groupby


【解决方案1】:

您可以在GroupBy 中循环访问不同的组:

for name, group in df.groupby('interview'):
    # perform some operations on group

【讨论】:

  • 当您运行 type(group) 时,它会返回元组...我需要访问数据帧,如何将这些组重新分配到 tmp 数据帧中?
  • 更新了答案
猜你喜欢
  • 2010-11-19
  • 2021-09-24
  • 1970-01-01
  • 2021-07-13
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多