python - 对每个 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
有没有更聪明的方法来做到这一点,这样它就不需要很长时间才能运行?谢谢!
解决方案
我们可以这样做explode
:merge
注意在 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],
}
推荐阅读
- c# - 将虚拟属性设置为 null 仅在调试时有效
- angular - Angular:如果localStorage中存在变量,如何重定向到给定的url?
- r - 将 PDF 文档传递给 R 函数
- javascript - 如何防止组件收集不必要的依赖?
- android - registerNotificationActions 不是 ReactNative 中的函数
- api - 无法从 API 获取任何数据
- javascript - 在 Google 条形图上,我无法删除没有数据的列
- html - 如何获取xpath的文本值?
- c - C89 中的 {0} 初始化程序有多标准?
- python - 使用python中的格式打印列中的n行