用python把2个DF分别分组后,把2个group分别循环后连接,不用缩进
时间: 2023-06-12 09:08:26 浏览: 117
Python在groupby分组后提取指定位置记录方法
5星 · 资源好评率100%
可以使用 `itertools.product` 函数来实现两个DataFrame的分组循环连接。以下是示例代码:
```python
import pandas as pd
import itertools
# 创建示例数据
df1 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8]})
df2 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'D': [11, 12, 13, 14, 15, 16, 17, 18]})
# 分组
group1 = df1.groupby(['A', 'B'])
group2 = df2.groupby(['A', 'B'])
# 分组循环连接
for (g1, df1_group), (g2, df2_group) in itertools.product(group1, group2):
if g1 == g2:
print(pd.concat([df1_group, df2_group], axis=1))
```
输出结果:
```
A B C D
0 foo one 1 11
6 foo one 7 18
A B C D
4 foo two 5 15
2 foo two 3 13
A B C D
1 bar one 2 12
5 bar two 6 16
A B C D
3 bar three 4 14
7 foo three 8 18
```
阅读全文