在一组熊猫数据框架上应用一个值



我试图总结每个类型匹配的每个组的值,并将其应用于store =1。

的行

下面的A组示例包含一个商店= 1和三个存储= 2。

我想汇总所有级别的3型3级= a = a商店= 1行

样本数据:

data = {'group':['A','A','A','A','B','B','B','B'],'store':['1','2','2','2','1','2','2','2'],'type':['3','3','1','1','5','0','5','5'],'num':['10','20','30','40','50','60','70','80']}
t1=pd.DataFrame(data)
group store type num    
A     1     3    10 
A     2     3    20 
A     2     1    30
A     2     1    40 
B     1     5    50 
B     2     0    60 
B     2     5    70 
B     2     5    80

和正确的输出应该是一个新列('new_num'(,其中包含在商店中的列表= 1行的类型匹配的1行。

group store type num new_num
A     1     3    10  ['10','20']
A     2     3    20  []
A     2     1    30  []
A     2     1    40  []
B     1     5    50  ['50','70','80']
B     2     0    60  []
B     2     5    70  []
B     2     5    80  []

iiuc

t1['new_num']=[[] for x in range(len(t1))]
t1.loc[t1.store=='1','new_num']=[y.loc[y.type.isin(y.loc[y.store=='1','type']),'num'].tolist() for x , y in t1.groupby('group',sort=False)]
t1
Out[369]: 
  group store type num       new_num
0     A     1    3  10      [10, 20]
1     A     2    3  20            []
2     A     2    1  30            []
3     A     2    1  40            []
4     B     1    5  50  [50, 70, 80]
5     B     2    0  60            []
6     B     2    5  70            []
7     B     2    5  80            []

setup

ncol = [[] for _ in range(t1.shape[0])]
res = t1.set_index('group').assign(new_num=ncol)

1(使用一些杂种弦乐和 groupby's

u = t1.group + t1.type
check = u[t1.store.eq('1')]
m = t1.loc[u.isin(check)].groupby('group')['num'].agg(list)
res.loc[res.store.eq('1'), 'new_num'] = m

2(如果您想从光线上偏离灯光,请使用pivot

的憎恶
f = t1.pivot_table(
  index=['group', 'type'],
  columns='store',
  values='num',
  aggfunc=list
).reset_index()
m = f[f['1'].notnull()].set_index('group').drop('type', 1).sum(1)
res.loc[res.store.eq('1'), 'new_num'] = m

两者都设法产生:

      store type num       new_num
group
A         1    3  10      [10, 20]
A         2    3  20            []
A         2    1  30            []
A         2    1  40            []
B         1    5  50  [50, 70, 80]
B         2    0  60            []
B         2    5  70            []
B         2    5  80            []

可怕的使用pivot,我实际上认为解决方案非常整洁:

store group type     1         2
0         A    1   NaN  [30, 40]
1         A    3  [10]      [20]
2         B    0   NaN      [60]
3         B    5  [50]  [70, 80]

它会产生上述聚合,您可以找到您所追求的所有匹配组型组合的非null值,并且在这些行之间进行总结为您提供所需的聚合列表。

>

最新更新