簡體   English   中英

獲取 dataframe 中的值組合並實現 function

[英]Get a combination of values in dataframe and implement a function

我想獲取列中的值組合並將 function 應用於每個組合。最簡單的方法是什么?

示例數據

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

我想要的結果
我在示例中使用 sum 作為 function :

| 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      |

筆記
我的 function 將“pandas.Series”作為參數。
例如:
x =一系列“6A”

y =一系列“6B”

6A_6B = sum(x,y)

我發現重塑數據更直接,然后是所有成對組合的簡單相加。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM