用大熊猫为每个组创建一个数据框组合(Create a DataFrame of combinations for each group with pandas)

编程入门 行业动态 更新时间:2024-10-09 13:33:39
用大熊猫为每个组创建一个数据框组合(Create a DataFrame of combinations for each group with pandas)

输入如下。

Out[178]: 
  group value
0     A     a
1     A     b
2     A     c
3     A     d
4     B     c
5     C     d
6     C     e
7     C     a
 

对于这个输入,我想为每个组创建一个组合并创建一个DataFrame。 我该怎么做?

我想要得到的输出:

Out[180]: 
  group  0  1
0     A  a  b
1     A  a  c
2     A  a  d
3     A  b  c
4     A  b  d
5     A  c  d
0     C  d  e
1     C  d  a
2     C  e  a

The inputs are as follows.

Out[178]: 
  group value
0     A     a
1     A     b
2     A     c
3     A     d
4     B     c
5     C     d
6     C     e
7     C     a
 

For this input, I want to create a combination for each group and create one DataFrame. How can I do it?

The output I want to get:

Out[180]: 
  group  0  1
0     A  a  b
1     A  a  c
2     A  a  d
3     A  b  c
4     A  b  d
5     A  c  d
0     C  d  e
1     C  d  a
2     C  e  a

                

最满意答案

使用lambda函数和combinations groupby :

from itertools import combinations df = (df.groupby('group')['value'].apply(lambda x: pd.DataFrame(list(combinations(x,2)))) .reset_index(level=1, drop=True) .reset_index()) print (df) group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 6 C d e 7 C d a 8 C e a

Use groupby with lambda function and combinations:

from itertools import combinations df = (df.groupby('group')['value'].apply(lambda x: pd.DataFrame(list(combinations(x,2)))) .reset_index(level=1, drop=True) .reset_index()) print (df) group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A b d 5 A c d 6 C d e 7 C d a 8 C e a

更多推荐

本文发布于:2023-08-04 18:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1419228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   大熊猫   创建一个   数据   Create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!