2016-02-29 43 views
2

我有一個熊貓dataFrame.After打印大熊貓數據框的結果看起來像下面用戶自定義JSON格式從熊貓據幀

country  branch  no_of_employee  total_salary count_DOB count_email 
    x   a   30     2500000  20   25 
    x   b   20     350000   15   20 
    y   c   30     4500000  30   30 
    z   d   40     5500000  40   40 
    z   e   10     1000000  10   10 
    z   f   15     1500000  15   15 

我想這個轉換成用戶定義的用戶格式像

{ 
     "x": [ 
     { 
      "Branch": "a", 
      "no_employee": 30 
     }, 
     { 
      "Branch": "b", 
      "no_employee": 20 
     } 

     ], 
     "y": [ 
     { 
      "Branch": "c", 
      "no_employee": 30 
     }, 
     { 
      "Branch": "d", 
      "no_employee": 40 
     } 

     ], 
     "z": [ 
     { 
      "Branch": "d", 
      "no_employee": 40 
     }, 
     { 
      "Branch": "e", 
      "no_employee": 10 
     }, 
     { 
      "Branch": "f", 
      "no_employee": 15 
     } 

    ] 

} 

如何將此數據框轉換爲此格式

回答

3

您可以嘗試groupbyapplyto_dict並且最後to_json

g = df.groupby('country')[["branch", "no_of_employee"]] 
               .apply(lambda x: x.to_dict(orient='records')) 
print g.to_json() 

{ 
    "x": [{ 
     "no_of_employee": 30, 
     "branch": "a" 
    }, { 
     "no_of_employee": 20, 
     "branch": "b" 
    }], 
    "y": [{ 
     "no_of_employee": 30, 
     "branch": "c" 
    }], 
    "z": [{ 
     "no_of_employee": 40, 
     "branch": "d" 
    }, { 
     "no_of_employee": 10, 
     "branch": "e" 
    }, { 
     "no_of_employee": 15, 
     "branch": "f" 
    }] 
} 
+0

@ jezrael no no我得到了確切的答案。我的意思是我想學習如何編寫這個函數,爲此目的我可以得到任何教程鏈接或其他東西 –

+0

所以我認爲你可以檢查[tutorial1](https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial /)或[tutorial2](http://www.diveintopython.net/power_of_introspection/lambda_functions.html)或[SO中的問題](http://stackoverflow.com/questions/890128/why-are -python-lambda表達式-有用)。但通常它會使編寫代碼變得更簡單,並且書面代碼更清晰一些。 – jezrael

+0

很高興能幫到你!祝你好運!美好的一天。 :) – jezrael