我有一個熊貓資料框df,如下所示:(下面是玩具版本,但真正的 df 包含更多列和groups)
group sub fruit
a 1 apple
a 2 banana
a 3 orange
b 1 pear
b 2 strawberry
b 3 cherry
c 1 kiwi
c 2 tomato
c 3 lemon
所有groups 具有相同的行數。我正在嘗試生成一個新的資料框,其中包含 的所有組合,group并sub通過從每個中隨機選擇 1 行group。
期望的輸出:
combo group sub fruit
1 a 1 apple
1 b 1 pear
1 c 1 kiwi
2 a 2 banana
2 b 2 strawberry
2 c 1 kiwi
3 a 3 orange
3 b 2 strawberry
3 c 1 kiwi
4 a 2 banana
4 b 2 strawberry
4 c 3 lemon
5 a 3 orange
5 b 3 cherry
5 c 3 lemon
...
在這個特定的例子中,我希望有 27 個不同combo的 s。這個例子似乎很有幫助,但我無法迭代地生成每個組合:Randomly select a row from each group using pandas
uj5u.com熱心網友回復:
您可以itertools.product在索引組上使用:
from itertools import product
out = pd.concat({i: df.loc[list(idx)] for i, idx in
enumerate(product(*df.index.groupby(df['group']).values()), start=1)})
輸出:
group sub fruit
1 0 a 1 apple
3 b 1 pear
6 c 1 kiwi
2 0 a 1 apple
3 b 1 pear
... ... ... ...
26 5 b 3 cherry
7 c 2 tomato
27 2 a 3 orange
5 b 3 cherry
8 c 3 lemon
[81 rows x 3 columns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531548.html
標籤:Python熊猫组合
