Python - 利用Dictionary處理數據

本文章將分享如何利用編程技術更有效地處理原始數據。 請參考之前的文章安裝Python和相關模組,並下載原始數據(JSON格式)。

在剛才的例子中,10個成員的年齡被提取並存儲在一個數組中。 在會員資料中,用戶有1個Primary Key(會員ID)和3個Attributes(姓名,性別,年齡), 因此我們需要建立三組陣列(List),並把這些資料儲存在它們中。
> (name, gender, age, ...) = ([], [], [], ...)    # multiple declare the arrays
> for i in range(len(raw_data["profile"])): 
       name.append(raw_data["profile"][i]["name"])
       gender.append(raw_data["profile"][i]["gender"])
       age.append(raw_data["profile"][i]["age"])

Another way is that a dictionary with key value can be used to store the member list from JSON data.
除了List,Dictionary也是用作儲存多個Elements的Data Type,以Key和Value作為一組來儲起每一個會員的資料,其格式跟JSON一樣,所以我們只需輸入已知的Key便能獲得它的Value。
> from pprint import pprint 
> members = {}    # declare a dictionary to store the member
> for i in range(len(raw_data["profile"])):
      mem_id = raw_data["profile"][i]["id"]    # mem_id is the key value of the list
      name = raw_data["profile"][i]["name"]
      gender = raw_data["profile"][i]["gender"]
      age = raw_data["profile"][i]["age"]
      members.setdefault(mem_id,{ })    # setdefault is the function put the key and values into a List
      members[mem_id] = (name, gender, age)
> members = sorted(members.items())    # Sort the value in dictionary with key value 
> pprint.pprint(members)    # List out the keys and values in member_list



Great! The data is loaded into dictionary. Do you remember that we calculated the mean of the age?
非常好!這些Data已加載上Dictionary,還記得計算年齡的平均值嗎?沒錯,用上公式:所有年齡的總和 / 會員的數目
> sum_age = 0
> for member in members:
        sum_age += member[1][2]
> sum_age / len(members)    # len is built-in function to get the number of elements in the list
# Looping 10 times to sum the age and then get the average
 is simplified to:
> numpy.mean([member[1][2] for member in members])
# Get the mean of 10 records of age which are listed by for-looping

為了先了解更多的變數,"member"是指"members" (Dictionary)中的其中一個顧客紀錄,而"member"中有3個elements,我們能用[ ]表示我們想獲得資料的位置,member[0]會拿到member_id,而member[1],會獲得一組陣列,裡面包括姓名,性別和年齡(位置: 0, 1, 2)。如果想取得年齡,可以用[2]表示我們想取得第3個elements,全句即是member[1][2]。

利用剛才的方法,如果我們想獲得一組年齡的數據,Python有一個方法叫List Comprehension,只需更少的Coding便能建立新的陣列,[members[1][2] for member in members] ,這會輪出一個陣列: [25, 13, 19, 26, 32, 29, 21, 24, 22, 19],若果我們想獲得年齡的平圴數,只需要便用剛才的公式或利用numpy.mean()這個function把這個陣列,便能直接獲得答案,十分方便。



Comments