Skip to main content
 首页 » 编程设计

python之您如何指定对其他列进行操作的 pandas groupby 和聚合操作

2024年09月07日8sky-heaven

我有一个 Pandas 数据框如下:

+----+-------+-------+ 
| id | col_1 | col_2 | 
+----+-------+-------+ 
|  1 | 1.2   |     0 | 
|  1 | 7.2   |     0 | 
|  1 | 12.1  |     1 | 
|  1 | 15.2  |     0 | 
|  1 | 16.3  |     1 | 
|  1 | 21.1  |     0 | 
|  1 | 22.2  |     0 | 
|  2 | 3     |     0 | 
|  2 | 5     |     1 | 
+----+-------+-------+ 

我如何使用 col_1 和 col_2 为每个 id 创建一个新列 (col_3) where 对于每个元素 I in col_1 if exists an element J in col_1 where

1) I < J <= I + 10 和 2) col_2中J的对应元素为1
col_3 为 1 否则为 0?

例如,上述数据框的 col_3 将是:

+----+-------+-------+-------+ 
| id | col_1 | col_2 | col_3 | 
+----+-------+-------+-------+ 
|  1 | 1.2   |     0 |     0 | 
|  1 | 7.2   |     0 |     1 | 
|  1 | 12.1  |     1 |     1 | 
|  1 | 15.2  |     0 |     1 | 
|  1 | 16.3  |     1 |     0 | 
|  1 | 21.1  |     0 |     0 | 
|  1 | 22.2  |     0 |     0 | 
|  2 | 3     |     0 |     1 | 
|  2 | 5     |     1 |     0 | 
+----+-------+-------+-------+ 

请您参考如下方法:

我用的是numpy方法

l=[] 
for _,x in df.groupby('id'): 
    s=(((x['col_1'].values > x['col_1'].values[:, None]) &(x['col_1'].values <= (x['col_1'].values[:, None] + 10))) & x['col_2'].values.astype(bool)).any(1).astype(int).tolist() 
    l.extend(s) 
 
 
df['col_3']=l 
df 
Out[400]:  
   id  col_1  col_2  col_3 
0   1    1.2      0      0 
1   1    7.2      0      1 
2   1   12.1      1      1 
3   1   15.2      0      1 
4   1   16.3      1      0 
5   1   21.1      0      0 
6   1   22.2      0      0 
7   2    3.0      0      1 
8   2    5.0      1      0