2017-11-30 2 views
1

너희들은 전에 내 질문에 매우 도움이되었다. 영숫자 값을 가진 인덱스를 정렬하려고했습니다. 오늘의 성공이 스크립트를 실행했지만 오류가 수신되었습니다데이터 조작 - 데이터 프레임 집계 함수 사용

/Library/Python/2.7/site-packages/pandas/core/groupby.py:4036: FutureWarning: using a dict with renaming is deprecated and will be removed in a future version 
    return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) 
Traceback (most recent call last) 
aggfunc={'sum': np.sum}, fill_value=0) 
    File "/Library/Python/2.7/site-packages/pandas/core/reshape/pivot.py", line 136, in pivot_table 
    agged = grouped.agg(aggfunc) 
    File "/Library/Python/2.7/site-packages/pandas/core/groupby.py", line 4036, in aggregate 
    return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) 

흔적 다시 피벗을 :이 오류 전에 적용한 유일한 변화가 있었다

df = df.pivot_table(index=['customer'], columns=['Duration'], 
                aggfunc={'sum': np.sum}, 
    fill_value=0) 

SQL 문에서 계산을 실행하는 대신 데이터 프레임의 하나의 데이터 열에 계산을 도입하십시오.

새로운 계산 :

df['Duration'] = df['Duration']/30 

올드 그룹 별 및 통합 :

df = df.pivot_table(index=['customer'], columns=['Duration'], 
              aggfunc={'sum': np.sum}, fill_value=0) 
c = df.columns.levels[1] 
c = sorted(ns.natsorted(c), key=lambda x: not x.isdigit()) 
df = df.reindex_axis(pd.MultiIndex.from_product([df.columns.levels[0], c]), axis=1) 

새로운 코드 스 니펫 : 새로운 접근 방식

df = df.groupby(['customer', 'Duration']).agg({'sum': np.sum}) 
c = df.columns.get_level_values(1) 
c = sorted(ns.natsorted(c), key=lambda x: not x.isdigit()) 
df = df.reindex_axis(pd.MultiIndex.from_product([df.columns.levels[0], c]), axis=1) 

다중 인덱스 레벨 :

MultiIndex(levels=[[u'Invoice A', u'Invoice B', u'Invoice C', u'Invoice B'], [u'0', u'1', u'10', u'11', u'2', u'2Y', u'3', u'3Y', u'4', u'4Y', u'5', u'5Y', u'6', u'7', u'8', u'9', u'9Y']], labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]], names=['customer', u'Duration']) 
IndexError: Too many levels: Index has only 1 level, not 2

입력 샘플 :

c = df.columns.get_level_values(1)을 할당, 나는 오류 메시지가 나타납니다

customer    Duration    sum   
Invoice A    1     1250 
Invoice B    2     2000 
Invoice B    3     1200 
Invoice C    2     10250 
Invoice D    3     20500 
Invoice D    5     18900 
Invoice E    2Y    5000 
Invoice F    1     5000 
Invoice F    1Y    12100 

확실하지 왜, 모두 레벨과 이름은 두 가지 수준이있다. 최종 결과는 customer으로 정렬되고 각 열은 Duration에 대해 sum을 표시하는 Duration 순으로 정렬되는 데이터 프레임입니다. 또한 이전 코드 버전에서 피벗을 사용하는 이유는 다음과 같은 출력 형식을 유지하기위한 것입니다.

Duration       2   2Y   3   3Y 
customer                  
Invoice A       2550  0.00  0.00  2000 
Invoice B       5000  2500  1050  0.00 
Invoice C       12500  0.00  1120  2050 
Invoice D       0.00  1500  0.00  8010 

올바른 트랙에 있습니까?

Data Manipulation - stackoverflow

+0

하드 찾을 수 있습니다. 어쩌면 당신은 이것을 찾고 있습니다 https://stackoverflow.com/questions/44635626/pandas-aggregation-warning-futurewarning-using-a-dict-with-renaming-is-depreca – Dark

+0

그리고 당신은 열의 수준을 찾고 있습니다. 'df.index.get_level_values'이어야합니다. – Dark

답변

1

당신은 instaed agg 기능 sum()를 사용하고 unstack으로 바꿀 : 실제 질문은 귀하의 질문에 어디

import natsort as ns 

df = df.groupby(['customer', 'Duration'])['sum'].sum().unstack() 

c = sorted(ns.natsorted(df.columns), key=lambda x: not x.isdigit()) 
df = df.reindex(columns=c) 
print (df) 
Duration  1  2  3  5  1Y  2Y 
customer              
Invoice A 1250.0  NaN  NaN  NaN  NaN  NaN 
Invoice B  NaN 2000.0 1200.0  NaN  NaN  NaN 
Invoice C  NaN 10250.0  NaN  NaN  NaN  NaN 
Invoice D  NaN  NaN 20500.0 18900.0  NaN  NaN 
Invoice E  NaN  NaN  NaN  NaN  NaN 5000.0 
Invoice F 5000.0  NaN  NaN  NaN 12100.0  NaN 
+0

jezrael - 당신의 솔루션이 좋아 보입니다. 'df.reindex (c, axis = 1)'에 이상한 오류가 발생했습니다. 'File "/Library/Python/2.7/site-packages/pandas/core/generic.py", 2494 줄, 다시 색인에 '인자 "{0}"'. (list (kwargs.keys()) [0 ])) TypeError : reindex()에서 예기치 않은 키워드 인수가 있습니다. "axis"' – OAK

+1

어쩌면 팬더의 마지막 버전 일 수도 있습니다. 'df = df.reindex (columns = c)' – jezrael

+0

on point. 고마워요! – OAK