2016-07-13 3 views
0

40 개의 열과 400000 개의 행이있는 팬더 데이터 프레임이 있습니다. 3 열의 데이터 세트를 만들었습니다.groupby pandas 데이터 프레임에 대한 산술 연산

이제 두 개의 열을 기반으로 % 메트릭을 계산해야합니다. 파이썬은 에러가 발생합니다 -

unsupported operand type(s) for /: 'SeriesGroupBy' and 'SeriesGroupBy' 

여기에 샘플 코드입니다 :

print sample_data 
    date part receipt bad_dollars total_dollars bad_percent 
0  1 123  22   40   100   NaN 
1  2 456  44   80   120   NaN 
2  3 134  33   30   150   NaN 
3  1 123  22   80   100   NaN 
4  5 456  45   40    90   NaN 
5  3 134  33   85   150   NaN 
6  7 123  24   70   120   NaN 
7  5 456  45   20    85   NaN 
8  9 134  35   50   300   NaN 
9  7 123  24   300   600   NaN 

sample_data_group = sample_data.groupby(['date','part','receipt']) 

sample_data_group['bad_percents']=sample_data_group['bad_dollars']/sample_data_group['total_dollars'] 

TypeError: unsupported operand type(s) for /: 'SeriesGroupBy' and 'SeriesGroupBy' 

도와주세요!

+0

당신의 "나쁜"또는 "전체"라는 어떤 열을 생성하지 않는 코드, 그래서 참조하려고 이해가되지 않습니다 그들. 문제를 보여주는 실제적이고 실행 가능한 자체 포함 된 예를 보여주십시오. – BrenBarn

답변

0

당신이이 GROUPBY 객체에 적용하여 수행 할 수 있습니다

import pandas as pd 
import numpy as np 

cols = ['index', 'date', 'part', 'receipt', 'bad_dollars', 'total_dollars', 'bad_percent'] 
sample_data = pd.DataFrame([[0,  1, 123,  22,   40,   100,   np.nan], 
[1,  2, 456,  44,   80,   120,   np.nan], 
[2,  3, 134,  33,   30,   150,   np.nan], 
[3,  1, 123,  22,   80,   100,   np.nan], 
[4,  5, 456,  45,   40,    90,   np.nan], 
[5,  3, 134,  33,   85,   150,   np.nan], 
[6,  7, 123,  24,   70,   120,   np.nan], 
[7,  5, 456,  45,   20,    85,   np.nan], 
[8,  9, 134,  35,   50,   300,   np.nan], 
[9,  7, 123,  24,   300,   600,   np.nan]], columns = cols).set_index('index', drop = True) 

sample_data_group = sample_data.groupby(['date','part','receipt']) 

xx = sample_data_group.apply(lambda x: x.assign(bad_percent = x.bad_dollars/x.total_dollars))\ 
         .reset_index(['date','part', 'receipt'], drop = True) 
관련 문제