[英]For loop through groups after pandas groupby on a dataFrame
我有以下 Pandas Dataframe 并创建了一个 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() 操作。 这可能吗?
还是可以通过MultiIndex
或其他方式使用reindex
来实现?
我假设无论顺序如何,您都不想重复相同的组对。 在这种情况下,您可以使用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):
# (...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.