首页 > 解决方案 > 对每个 ID 的关联 ID 求和布尔值并将其分配给 ID

问题描述

我有一个名为复合的数据框,如下所示:

| ID | Person.ID | V.F   | V.nF  |
|----|-----------|-------|-------|
| 1  | 111       | True  | True  |
| 2  | 222       | False | True  |
| 3  | 333       | True  | False |
| 4  | 444       | True  | False |
| 5  | 555       | True  | True  |
| 6  | 666       | False | True  |

对于每个 Person.ID,在一个名为nn_list的字典中,我拥有每个 Person.ID 的所有关联 Person.ID。这看起来像:

{ 111:[222,333,444],
222:[111,333],
333:[444],
444:[222,555],
555:[333,666],
666:[222],
}

我希望能够查看给定 ID 的所有关联 Person.ID 的字典,对关联 ID 的布尔值(每列)求和,然后将该值分配到新列中每一行。结果看起来像这样:

| ID | Person.ID | V.F   | V.nF  | n_V.F | n_V.nF |
|----|-----------|-------|-------|-------|--------|
| 1  | 111       | True  | True  | 2     | 1      |
| 2  | 222       | False | True  | 2     | 1      |
| 3  | 333       | True  | False | 1     | 0      |
| 4  | 444       | True  | False | 1     | 2      |
| 5  | 555       | True  | True  | 1     | 1      |
| 6  | 666       | False | True  | 0     | 1      |

我目前能够以非常缓慢且低效的方式执行此操作:

l=[composite.loc[composite['Person.ID'].isin(nn_list[x]),'V.F'].sum() for x in composite['Person.ID']]
composite['n_V.F']=l

l=[composite.loc[composite['Person.ID'].isin(nn_list[x]),'V.nF'].sum() for x in composite['Person.ID']]
composite['n_V.nF']=l

有没有更聪明的方法来做到这一点,这样它就不需要很长时间才能运行?谢谢!

标签: pythonpandas

解决方案


我们可以这样做explodemerge注意在 0.25 之后可以使用爆炸pandas

s=pd.Series(d).explode().to_frame('Person.ID').reset_index()
s=s.merge(df).groupby('index')[['V.F','V.nF']].sum()
Newdf=pd.concat([df.set_index('Person.ID'),s.add_prefix('n_')],axis=1).reset_index()
Newdf
   index  ID    V.F   V.nF  n_V.F  n_V.nF
0    111   1   True   True    2.0     1.0
1    222   2  False   True    2.0     1.0
2    333   3   True  False    1.0     0.0
3    444   4   True  False    1.0     2.0
4    555   5   True   True    1.0     1.0
5    666   6  False   True    0.0     1.0

d={ 111:[222,333,444],
222:[111,333],
333:[444],
444:[222,555],
555:[333,666],
666:[222],
}

推荐阅读