1. 程式人生 > >python--從字典中提取子字典並轉成DataFrame的方法

python--從字典中提取子字典並轉成DataFrame的方法

【問題描述】

我想從已有字典中提取出幾個鍵值對構成新的字典,然後為了方便檢視,再轉成DataFrame格式。

【問題解決】

test_0 = {"id":[1,1,2,3,3,4,5,5],"price":[5,6,8,3,4,6,9,5],"amount":[1,1,2,1,1,1,2,1],"status":['sale','sale','no','no','sale','no','sale','no']} 
type(test_0)
dict

我想得到只包含'id','price','amount'的子字典,解決辦法如下:

index = {'id','price','amount'}   #建立一個set來儲存想要的key
test_1 = {key:value for key,value in test_0.items()if key in index}   #建立子字典   
test_1
{'amount': [1, 1, 2, 1, 1, 1, 2, 1],
 'id': [1, 1, 2, 3, 3, 4, 5, 5],
 'price': [5, 6, 8, 3, 4, 6, 9, 5]}

出了篩選想要的key之外,還可以篩選value(把if後面的條件改成關於value的即可,如if value > 1)

接著我想把得到的子字典轉化為DataFrame格式

pd.DataFrame(test_1)

發現是我們想要的樣子。(還好,還好。。。)

問題解決!

(僅供個人學習,不負責任~~~~~~~~~~~~~~~)