【问题标题】:For loop through groups after pandas groupby on a dataFrame在数据帧上的 pandas groupby 之后循环遍历组
【发布时间】:2021-12-28 01:13:29
【问题描述】:

我有以下 pandas 数据框并创建一个 groupby 对象:

df = pd.DataFrame({'Colors': ['blue', 'blue', 'orange',
                              'purple', 'orange', 'purple', 'blue'], 
                   'Price': ['500', '500', '200', '300', '765', '1100', '762', 
                              '650'],
                   'Style': ['farm', 'contemporary', 'modern', 'MDM', 
                             'contemporary', 'farm', 'contemporary'],
                   'Location': ['far', 'near', 'far', 'far', 'near', 'far', 'far', 
                                'near']})

grouped_df = df.groupby(['Colors', 'Price', 'Style', 'Location'])

Groups in grouped_df are: 

grouped_df = 

Colors   Price   Style         Location
blue     500     contemporary  near
                 farm          far
         650     contemporary  near
orange   1100    contemporary  far
         250     modern        far
purple   762     farm          far
         765     MDM           near

我可以通过以下方式迭代组:

for name, group in grouped_df:
    ..........

但是如何在所有组对上执行嵌套 for 循环以对每个唯一组对执行操作?明确地说,它有点像使用组 1 并与其他组迭代所有唯一对,移动到组 2 并做同样的事情并重复。具体来说,每个操作最终都会成为对组对的 pd.merge() 操作。这可能吗?

或者可以使用reindex by MultiIndex 或其他方式来实现吗?

【问题讨论】:

  • 你的预期输出是什么?

标签: python pandas for-loop group-by pandas-groupby


【解决方案1】:

我假设无论顺序如何,您都不想重复相同的组对。在这种情况下,您可以使用itertools.combinations

import itertools as it

grouped_df = df.groupby(['Colors', 'Price', 'Style', 'Location'])

for (name1, group1), (name2, group2) in it.combinations(grouped_df, 2):
    # (...)

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2021-12-15
    • 2019-10-18
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-11-22
    相关资源
    最近更新 更多