2015-01-18 6 views
0

장고 모델 데이터베이스 EAV 스키마에 NumPy와 배열을 분류 :삽입 나는 형식의 팬더 피벗 테이블이

income_category  age_category  income   age 
High    Middle aged  123,564.235 23.456 
Medium    Old    18,324.356  65.432 

내가 자체 참조 테이블에 label들 일치하는 범주 계층 구조를 가지고 dimension 전화를 . 즉,

dimension_id  label    parent_dimension_id 
1     Age categories 
2     Young    1 
3     Middle aged  1 
4     Old    1 

...and similarly for income 

은 정말 무작위로 해당 행에 시간과 액세스 세포에서 행을 선택하기 위해 사투를 벌인거야.

상위 카테고리 ID는 dimension_id이며 아래 코드는 이미 cat_id_age입니다. 따라서 Numpy 배열을 반복하면서 해당 행에 일치하는 범주 dimension_id을 가져 와서 해당 값과 함께 값 테이블에 삽입하려고합니다. 그러나 나는 이것을 Python이나 Djangonically하는 방법을 모른다. (. 내가 dimension_id을 찾는 아래의 사전 접근 방식이 최고라고 생각 때문에 몇 종류가 있습니다) 내 반복 마음에 프로세스는 다음과 같습니다 그러나이 같은 반복과 사투를 벌인거야

# populate a Dictionary to find dimension_ids 
age_dims = Dimension.objects.filter(parent_id=cat_id_age).values('label', 'id') 

for row in Numpy_array: 

    dim_id = Dimension.get(row.age_category) 

    # Or is the Dict approach incorrect? I'm trying to do: SELECT dimension_id FROM dimension WHERE parent_dimension_id=cat_id_age AND label=row.age_category 
    # Djagonically? dim = Dimension.objects.get(parent_id=cat_id_age, label=row.age_category) 

    # Then insert categorized value, ie, INSERT INTO float_value (value, dimension_id) VALUES (row.age, dimension_id) 
    float_val = FloatValue(value=row.age, dimension_id=dim_id) 
    float_val.save() 

...then repeat for income_category and income. 

- 할 수 내 유일한 문제가 있지만 나는 종종 내가 패러다임 떨어져 파이썬 (예 : cursor.executemany("""insert values(?, ?, ?)""", map(tuple, numpy_arr[x:].tolist()))처럼 sth)처럼 보이려고 내가 뭘 하려는지 의사 소통을 위해 나머지를 포함 시켰습니다.

모든 포인터 정말 감사하겠습니다. (저는 장고 1.7과 파이썬 3.4를 사용하고 있습니다.)

+0

[숙제를하고 내 질문에 더 집중할 때] 누군가 대답 할 수있었습니다. (http://stackoverflow.com/questions/28097319/how-can-i-iterate-over-pandas-pivot-table- a-multi-index-dataframe) Anzel에게 감사드립니다. – Chris

답변

1

Anzel은 반복 문제 here에 대답했습니다 - the Pandas to_csv() function을 사용하십시오. 내 사전 구문도 잘못되었습니다. 내 최종 솔루션 그러므로했다 : 엔티티 - 속성 - 값에 대한 자세한 내용은

# populate a Dictionary to find dimension_ids for category labels 
parent_dimension_age = Dimension.objects.get(name='Age') 
parent_dimension_income = Dimension.objects.get(name='Income') 
dims_age = dict([ (d.name, d.id) for d in Dimension.objects.filter(parent_id=parent_dimension_age.id) ]) 
dims_income = dict([ (d.name, d.id) for d in Dimension.objects.filter(parent_id=parent_dimension_income.id) ]) 

# Retrieves a row at a time into a comma delimited string 
for line in pandas_pivottable.to_csv(header=False, index=True, sep='\t').split('\n'): 
    if line: 
     # row[0] = income category, row[1] = age category, row[2] = age, row[3] = income 
     row = line.split('\t') 
     entity = Entity(name='data pivot row', dataset_id=dataset.id) 
     entity.save() 
     # dims_age.get(row[1]) gets the ID for the category whose name matches the contents of row[1] 
     age_val = FloatValue(value=row[2], entity_id=entity.id, attribute_id=attrib_age.id, dimension_id=dims_age.get(row[1])) 
     age_val.save() 
     income_val = FloatValue(value=row[3], entity_id=entity.id, attribute_id=attrib_income.id, dimension_id=dims_income.get(row[0])) 
     income_val.save() 

(당신이 the Django-EAV extension를 참조 고려하고있는 경우) (EAV) 스키마, the Wikipedia page를 참조하십시오. 그러나이 프로젝트의 다음 반복에서는 postgresql's new JSONB type으로 바꿀 것입니다. 이는 데이터를보다 읽기 쉽고 동일하게 또는 더 잘 수행 할 수 있도록 보장합니다.