2017-09-27 6 views
1

これまでにPandasを使ったことはありません。私はcsvデータからjsonへの非常に簡単な変換を試みています。csvデータをjsonにPandasを使ってグループ化する

私のCSVデータの形式は次のとおりです。

Category | Type | Parameter Name | Parameter Value 
---------|------|----------------|---------------- 
Windows | W1 | Width   | 900 
Windows | W1 | Height   | 900 
Windows | W2 | Width   | 1200 
Windows | W2 | Height   | 500 
Doors | D1 | Width   | 900 
Doors | D1 | Height   | 2100 
Doors | D2 | Width   | 820 
Doors | D2 | Height   | 2100 

そして、私のようなものを生成します:

{ 
    "Windows": { 
     "W1": { 
      "Height": 900, 
      "Width": 900 
     }, 
     "W2": { 
      "Height": 500, 
      "Width": 1200 
     }, 
    }, 
    "Doors: { 
     "D1": { 
      "Height": 2100, 
      "Width": 900 
     }, 
     "D2": { 
      "Height": 2100, 
      "Width": 500 
     }, 
    }, 
} 

を誰が助けることはできますか?

+0

パンダDATAFRAMEは、関数は()とto_jsonを()read_csvあり得る願っています。 – Dan

+0

ええ、csvをデータフレームに変換してもOKですが、ネストされた形式にグループ化する方法がわかりません – sean2000

答えて

0

これ以上行う時間がありませんでした。これは

s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]] 

def redict(s): 
    if s.index.nlevels == 1: 
     return s.to_dict() 
    else: 
     return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)} 

redict(s) 

{'Doors': {'D1': {'Height': 2100, 'Width': 900}, 
    'D2': {'Height': 2100, 'Width': 820}}, 
'Windows': {'W1': {'Height': 900, 'Width': 900}, 
    'W2': {'Height': 500, 'Width': 1200}}} 

を助け、若干の修正を加えて、我々はjson

s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]] 

def redict(s): 
    if s.index.nlevels == 1: 
     return s.astype(str).to_dict() 
    else: 
     return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)} 

json.dumps(redict(s)) 

'{"Doors": {"D1": {"Width": "900", "Height": "2100"}, "D2": {"Width": "820", "Height": "2100"}}, "Windows": {"W1": {"Width": "900", "Height": "900"}, "W2": {"Width": "1200", "Height": "500"}}}' 
+0

ありがとう! – sean2000

関連する問題