2017-10-16 4 views
1

内の他のフィールドに現在のデータを使用して展開するには、私は(いくつかのネストされた)JSONの1つのフィールド内のフォーマットのデータを持って提案:開梱JSONとパンダ

Name  Identifier    Data 
Joe  54872      [{"ref":{"type":4,"id":86669},"side":"Buy","ratio":1},{"ref":{"type":4,"id":80843},"side":"Sell","ratio":1}] 
Jill  84756      [{"ref":{"type":4,"id":75236},"side":"Buy","ratio":1},{"ref":{"type":4,"id":75565},"side":"Sell","ratio":1}] 

単純な方法ではなく、JSONを開梱はありますそれ自身のデータフレームに挿入し、len(n)の各行の固定データと連結します(nは各jsonデータフレームの長さです)。

Name  Identifier  ref_type  ref_id  side  ratio 
Joe  54872   4    86669  buy  1 
Joe  54872   4    80843  sell  1 
Jill  84756   4    75236  buy  1 
Jill  84756   4    75565  sell  1 

ありがとう。

from pandas.io.json import json_normalize 
import json 

with open('file.json') as data_file:  
    data = json.load(data_file) 

df = json_normalize(data) 

EDIT:

ていない場合は使用の可能性:

+0

'プリント(DFの[ 'データ']は何を(適用しますタイプ)) '? – jezrael

+0

306 358 360 名前:データ、dtype:オブジェクト – jjm

+0

入力はjsonファイルですか?答えに私のソリューションを使用することは可能ですか? – jezrael

答えて

1

私は最高のjson_normalize使用していると思います。

import ast 
from pandas.io.json import json_normalize 

#convert strings to lists and dicts 
df['Data'] = df['Data'].apply(ast.literal_eval) 
#parse Data column 
df1 = pd.concat([json_normalize(x) for x in df['Data'].values.tolist()], keys= df.index) 
#append to original 
df1 = df.drop('Data', 1).join(df1.reset_index(level=1, drop=True)).reset_index(drop=True) 
print (df1) 
    Name Identifier ratio ref.id ref.type side 
0 Joe  54872  1 86669   4 Buy 
1 Joe  54872  1 80843   4 Sell 
2 Jill  84756  1 75236   4 Buy 
3 Jill  84756  1 75565   4 Sell 
+0

後者は非常にうまく動作します。ありがとうございました。 – jjm

関連する問題