2016-08-18 16 views
1

私はthis Amazon sample Snap grocery JSON dataをIBM Bluemix(Python 2.xを使用)のPandasデータフレームに変換しようとしていて、それをApache Sparkで解析しようとしています。非厳密なJSON Amazon SNAPメタデータをPandas DataFrameに変換

JSONファイルを解凍してApache Spark Containerにアップロードしました。ここで

は私のコンテナの接続です:私は、私はその後、追加することにより、厳格なJSONパターンに文字列のコンテンツを変換したStringIO

# In[ ]: 

import requests, StringIO, pandas as pd, json, re 


    # In[ ]: 

    def get_file_content(credentials): 
     """For given credentials, this functions returns a StringIO object containing the file content.""" 

     url1 = ''.join([credentials['auth_url'], '/v3/auth/tokens']) 
     data = {'auth': {'identity': {'methods': ['password'], 
       'password': {'user': {'name': credentials['username'],'domain': {'id': credentials['domain_id']}, 
       'password': credentials['password']}}}}} 
     headers1 = {'Content-Type': 'application/json'} 
     resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1) 
     resp1_body = resp1.json() 
     for e1 in resp1_body['token']['catalog']: 
      if(e1['type']=='object-store'): 
       for e2 in e1['endpoints']: 
        if(e2['interface']=='public'and e2['region']==credentials['region']): 
         url2 = ''.join([e2['url'],'/', credentials['container'], '/', credentials['filename']]) 
     s_subject_token = resp1.headers['x-subject-token'] 
     headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'} 
     resp2 = requests.get(url=url2, headers=headers2) 
     return StringIO.StringIO(resp2.content) 

にコンテナからデータをインポートするApacheのスパークのサンプルを使用

# In[ ]: 

credentials_1 = { 
    'auth_uri':'', 
    'global_account_auth_uri':'', 
    'username':'myUname', 
    'password':"myPw", 
    'auth_url':'https://identity.open.softlayer.com', 
    'project':'object_storage_988dfce6_5b93_48fc_9575_198bbed3abfc', 
    'project_id':'2c05de8a36d74d32bdbe0eeec7e5a372', 
    'region':'dallas', 
    'user_id':'4976489bab7d489f8d2eba681adacb78', 
    'domain_id':'8b6bc3e989d644858d7b74f24119447a', 
    'domain_name':'1079761', 
    'filename':'meta_Grocery_and_Gourmet_Food.json', 
    'container':'grocery', 
    'tenantId':'s31d-8e24c13d9c36f4-43b43b7b993d' 
} 

[と]最初と最後に、コンマでデータを区切ってください。

print('----------------------\n') 

import json 

myDf=[]; 

def parse(data): 
    for l in data: 
     yield json.dumps(eval(l)) 

def getDF(data): 
    st='[' 
    i = 0 
    df =[] 
    for d in parse(data): 
     if i<100: 
      i += 1 
      #print(str(d)) 
      st=st+str(d)+',' 
      #print('----------------\n') 
    st=st[:-1] 
    st=st+']' 
    #js=json.loads(st) 
    #print(json.dumps(js)) 
    return pd.read_json(st) 

content_string = get_file_content(credentials_1) 

df = getDF(content_string) 
df.head() 

私は完全に望ましい結果を得ています。 Output of the code

問題は、私が<条件を削除すると、決して完了せず、カーネルは1時間以上ビジーのままです。

データをデータフレームに変換する他のエレガントな方法はありますか?

また、ijsonはBluemixノートブックでは使用できません。

答えて

0

は私は2つの部分でこれを答えてみましょう: -

  1. あなたは、さらにあなたの使用ごとにそれを使用するコマンドの下に使用してbluemixスパークサービスにijsonをインストールし、ユーザーimport ijsonことができます。

    !pip install --user ijson

  2. あなたのスキーマを定義するために周りに行くのではなく、オブジェクトストレージからJSONを読み取るためにsqlContext.jsonFileを使用することができます。 これにより、スキーマが推測され、spark-sqlクエリを実行して、データフレームで必要な処理を実行できます。ここで

    df = sqlContext.jsonFile("swift://" + objectStorageCreds['container'] + "." + objectStorageCreds['name'] + "/" + objectStorageCreds['filename'])

notebookを完了するためのリンクです。

あなたはパンダのデータフレームで動作するように持っている場合は、単に

df.toPandas().head() 

に変換することができます。しかし、これは(慎重に使用)ドライバノードですべてを取得するようになります。

ありがとう、 チャールズ。

+0

驚くばかりです。ありがとうございます。私のケースでは単純な変更だけで、URLパターンを変更する必要がありました。 df = sqlContext.read.json( "swift://" + objectStorageCreds ['container'] + ".spark" + "/" + objectStorageCreds ['filename']) ".spark"はApache sparkでの作業に必要なようです。したがって、objectStorageCreds ['name']は 'spark'に設定できます。再度、感謝します。魅力のように動作します。 –

関連する問題