按所有类别分组,汇总功能,并在熊猫中填写所得的NA

时间:2019-03-12 12:10:08

标签: python pandas pandas-groupby

我有以下问题。

mtx =[['0','q'],
      ['0','e'],
      ['1','q'],
      ['1','w'],
      ['2','r'],
      ['2','e'],
      ['2','w'],
      ['3','t'],
      ['4','y']]
df10 = pd.DataFrame(np.insert(mtx, 2, np.random.rand(len(mtx))*10, axis=1),
                    columns=['id','cat','val'])

我想

  1. id cat 将其分组,
  2. 每个 id
  3. 中所有可能出现的 cat
  4. val
  5. 上应用函数(例如 sum
  6. 对于缺少(id,cat)的组合,请填写0。

即结果将具有以下形式。

mtx1 = [[el1, el] for el in 'qwerty' for el1 in '01234']
df11 = pd.DataFrame(np.insert(mtx1, 2, '-', axis=1), 
                    columns=['id','cat','val'])
>>>
[['0' 'q' '-']
 ['1' 'q' '-']
 ['2' 'q' '-']
 ['3' 'q' '-']
 ['4' 'q' '-']
 ['0' 'w' '-']
 ['1' 'w' '-']
 ['2' 'w' '-']
 ['3' 'w' '-']
 ['4' 'w' '-']
 ['0' 'e' '-']
 ['1' 'e' '-']
 ['2' 'e' '-']
 ['3' 'e' '-']
 ['4' 'e' '-']
 ['0' 'r' '-']
 ['1' 'r' '-']
 ['2' 'r' '-']
 ['3' 'r' '-']
 ['4' 'r' '-']
 ['0' 't' '-']
 ['1' 't' '-']
 ['2' 't' '-']
 ['3' 't' '-']
 ['4' 't' '-']
 ['0' 'y' '-']
 ['1' 'y' '-']
 ['2' 'y' '-']
 ['3' 'y' '-']
 ['4' 'y' '-']]

对于-,应该有func应用或为0的结果。 可以在熊猫中惯用地执行这种操作吗?与.groupby?我只能想到手动创建叉积,然后检查原始df10是否存在组合,然后应用func或在原始{{ 1}}。

0 个答案:

没有答案