2016-06-30 1 views
3

데이터베이스를 쿼리하고 결과를 데이터 프레임으로 저장 한 다음 factorizepivot_table으로 변환합니다. 이것은 데이터베이스 쿼리가 데이터를 반환 할 때 제대로 작동하지만 데이터가 반환되지 않을 때 오류가 발생합니다 (예상 됨). 이 예외를 잡아서 빈 데이터 프레임을 반환하는 방법?예외를 catch하고 빈 데이터 프레임을 반환합니다.

#When dataframe is non-empty, transformation works fine: 
print df 

    sale name year 
0 41 Jason 2012 
1 24 Molly 2012 
2 31 Jason 2013 
3 32 Jason 2014 
4 31 Molly 2014 


df['groups'] = (pd.factorize(df.year)[0] + 1).astype(str) 

df1 = (df.pivot_table(index='name', columns='groups', values=['sale', 'year'])) 
df1.columns = [''.join(col) for col in df1.columns] 
print (df1) 

     sale1 sale2 sale3 year1 year2 year3 
name            
Jason 41.0 31.0 32.0 2012.0 2013.0 2014.0 
Molly 24.0 NaN 31.0 2012.0  NaN 2014.0 

#But when dataframe is empty, factorize by pivot_table throws error 

df = pd.DataFrame(columns=['sales','name','year']) 
df1 = (df.pivot_table(index='name', columns='groups', values=['sale', 'year'])) 
df1.columns = [''.join(col) for col in df1.columns] 
print (df1) 

DataError: No numeric types to aggregate

답변

3
try: 
    df1 = df.pivot_table(index='name', columns='name', values=['sale', 'year']) 
except pd.core.groupby.DataError: 
    df1 = pd.DataFrame() 
except: 
    raise 

크레딧을 호출하기 전에 How can I catch a pandas DataError?

0

당신은 아마 dataframe가 비어 있는지 확인하거나 안

if df.empty: 
    return df 

dataerror에 대한 오류 이름을 발견하는 사람들 brenbarn하는 pivot_table

관련 문제