多索引对象熊猫的每个组的计算

时间:2020-01-25 14:03:21

标签: python pandas

我想为groupby对象的每个组计算一个值,但对组的每一行重复一次。 Calculation within Pandas dataframe group尽管标题似乎是我所需要的,但这不起作用。 我看不出该公式是否有问题。它应该是excel词汇中的总和。

dat = pd.DataFrame({'Supplier': ['A', 'A', 'A', 'B','B'], 'Id': ['1','2','3','4','5'], 'a': [2,2,2,2,2], 'AVG' :[5,6,7,8,3], 'BP': [3,4,5,6,3], 'Hc': [0.15,0.15,0.15,0.15,0.15]})

dat = dat.groupby(['Supplier', 'Id'])['a','AVG', 'BP','Hc'].sum()



for supplier in dat.index[0]:
    dat['s'] = np.sqrt((2 * (dat['a'])/ (
        ((dat['AVG'] * dat['BP'] * (dat['Hc']/4)).sum()))))

我得到的结果是:

             a  AVG  BP    Hc         s
Supplier Id                            
A        1   2    5   3  0.15  0.902358
         2   2    6   4  0.15  0.902358
         3   2    7   5  0.15  0.902358
B        4   2    8   6  0.15  0.902358
         5   2    3   3  0.15  0.902358

但是我想得到类似的东西:

             a  AVG  BP    Hc         s
Supplier Id                            
A        1   2    5   3  0.15  x
         2   2    6   4  0.15  x
         3   2    7   5  0.15  x
B        4   2    8   6  0.15  y
         5   2    3   3  0.15  y

这里的x和y表示每个“组”的数字应该不同

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

groupby.apply函数使您可以访问每个组(供应商)数据框。

def cal_func(df):
    df['s'] = np.sqrt((2 * (df['a'])/ (
        ((df['AVG'] * df['BP'] * (df['Hc']/4)).sum()))))
    return df

dat_new = dat.groupby(['Supplier']).apply(cal_func)
dat_new

  Supplier Id  a  AVG  BP    Hc         s
0        A  1  2    5   3  0.15  1.200600
1        A  2  2    6   4  0.15  1.200600
2        A  3  2    7   5  0.15  1.200600
3        B  4  2    8   6  0.15  1.367971
4        B  5  2    3   3  0.15  1.367971

答案 1 :(得分:0)

$this->db->select_max("auto_no");
$query = $this->db->get('letter_letter');
if ($query->num_rows() > 0) {
    $last_auto_no = $query->row()->auto_no;
    $no = intval(explode('-', $last_auto_no)[1]) + 1;
    $auto_no = date("Y").'-' . str_pad($no, $digits, "0", STR_PAD_LEFT);
} else {
    $auto_no = (date("Y").'-' . str_pad(0, $digits, "0", STR_PAD_LEFT));
}
return $auto_no