【问题标题】:Get a combination of values in dataframe and implement a function获取数据框中的值组合并实现函数
【发布时间】:2019-11-08 16:08:10
【问题描述】:

我想在一列中取值的组合,并对每个组合应用一个函数。最简单的方法是什么?

示例数据

| name | value |
|------|-------|
| 6A   | 1     |
| 6A   | 1     |
| 6A   | 1     |
| 6B   | 3     |
| 6B   | 3     |
| 6B   | 3     |
| 6C   | 7     |
| 6C   | 5     |
| 6C   | 4     |

我想要的结果
我在示例中使用 sum 作为函数:

| pair  | result |
|-------|--------|
| 6A_6B | 4      |
| 6A_6B | 4      |
| 6A_6B | 4      |
| 6A_6C | 8      |
| 6A_6C | 6      |
| 6A_6C | 5      |
| 6B_6C | 10     |
| 6B_6C | 8      |
| 6B_6C | 7      |

注意
我的函数以“pandas.Series”为参数。
例如:
x=一系列“6A”

y=一系列“6B”

6A_6B = sum(x,y)

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    我发现重塑数据更直接,然后是所有成对组合的简单相加。

    import pandas as pd
    from itertools import combinations
    
    u = (df.assign(idx = df.groupby('name').cumcount()+1)
           .pivot(index='idx', columns='name', values='value'))
    #name  6A  6B  6C
    #idx             
    #1      1   3   7
    #2      1   3   5
    #3      1   3   4
    
    l = []
    for items in combinations(u.columns, 2):
        l.append(u.loc[:, items].sum(1).to_frame('result').assign(pair='_'.join(items)))
    
    df = pd.concat(l)
    

         result   pair
    idx               
    1         4  6A_6B
    2         4  6A_6B
    3         4  6A_6B
    1         8  6A_6C
    2         6  6A_6C
    3         5  6A_6C
    1        10  6B_6C
    2         8  6B_6C
    3         7  6B_6C
    

    【讨论】:

      【解决方案2】:

      itertools.combinations

      想不通

      from itertools import combinations
      
      g = dict(tuple(df.groupby('name')))
      
      pd.DataFrame([
          (f'{x}_{y}', a + b)
          for x, y in combinations(g, 2)
          for a, b in zip(g[x]['value'], g[y]['value'])
      ], columns=df.columns)
      
          name  value
      0  6A_6B      4
      1  6A_6B      4
      2  6A_6B      4
      3  6A_6C      8
      4  6A_6C      6
      5  6A_6C      5
      6  6B_6C     10
      7  6B_6C      8
      8  6B_6C      7
      

      【讨论】:

      • 你好。我已经查看了您的代码。我在问题中添加了注释。请您检查一下吗?
      猜你喜欢
      • 2019-10-04
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多