Skip to main content
 首页 » 编程设计

python之为每个 ID 的关联 ID 求和 bool 值并将其分配给 ID

2024年11月01日10Free-Thinker

我有一个名为 composite 的数据框,它看起来像这样:

| 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 的 bool 值(每列)求和,然后在新列中分配该值( s) 每行。结果看起来像这样:

| 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 

有没有更聪明的方法来执行此操作,这样它就不会花费很长时间运行?谢谢!

请您参考如下方法:

我们可以执行 explode 然后 merge :注意 explode 在 pandas

0.25 之后可用
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], 
}