2016-10-11 9 views
1

배열에 포함 된 여러 사전을 팬더 데이터 프레임으로 변환하려고합니다. dicts 같은 저장됩니다중첩 된 배열을 파이썬에서 팬더 데이터 프레임으로 변환

[[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886', 
u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209', 
u'longitude': u'0.490475'},u'month': u'2015-02'}]] 

나는 아래의 형식으로 내 데이터의 형식을 시도하고있다 :

 Category  Latitude Longitude 
0 anti-social 524498.597 175181.644 
1 anti-social 524498.597 175181.644 
2 anti-social 524498.597 175181.644 
. ...   ... 
. ...   ... 
. ...   ... 

나는 아래의 코드와 dataframe에 데이터를 강제로하려했지만 의도 된 출력을 생성하지 않습니다.

for i in crimes: 
    for x in i: 
     print pd.DataFrame([x['category'], x['location']['latitude'], x['location']['longitude']]) 

저는이 데이터 프레임을 구축하는 데 도움이되는 모든 링크/팁을 매우 유용하게 사용합니다.

답변

1

올바른 길을 가고 있지만 올바른 행을 제공하지 않고 columns이라는 새로운 데이터 프레임을 만들고 있습니다. 다음 코드는 작동합니다 :

import pandas as pd 
import numpy as np 

crimes = [[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886', 
u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209', 
u'longitude': u'0.490475'},u'month': u'2015-02'}]] 

# format into a flat list 
formatted_crimes = [[x['category'], x['location']['latitude'], x['location']['longitude']] for i in crimes for x in i] 

# now pass the formatted list to DataFrame and label the columns 
df = pd.DataFrame(formatted_crimes, columns=['Category', 'Latitude', 'Longitude']) 

결과는 다음과 같습니다

   Category Latitude Longitude 
0 anti-social-behaviour 52.309886 0.496902 
1 anti-social-behaviour 52.306209 0.490475 
관련 문제