2015-12-04 46 views
1

我從MongoDB中獲取數據通過pymongo到Python,然後將其轉換成數據幀的大熊貓如何連接pandas中的數據框?

df = pd.DataFrame(list(db.dataset2.find())) 

這是數據看起來像在MongoDB中。

"dish" : [ 
     { 
     "dish_id"   : "005" , 
     "dish_name"  : "Sandwitch", 
     "dish_price"  : 50, 
     "coupon_applied" : "Yes",    
     "coupon_type"  : "Rs 20 off" 
     }, 
     { 
     "dish_id"   : "006" , 
     "dish_name"  : "Chicken Hundi", 
     "dish_price"  : 125, 
     "coupon_applied" : "No", 
     "coupon_type"  : "Null" 

     } 
    ], 

我想在pandas數據框中將菜屬性分成兩行。這是做這個的代碼。 (有3個碟文件),所以我通過for循環迭代它。

for i in range(0,len(df.dish)): 
data_dish = json_normalize(df['dish'][i]) 
print data_dish 

但它給了我下面的輸出..

coupon_applied coupon_type dish_id  dish_name  dish_price 
0   Yes Rs 20 off  001  Chicken Biryani   120 
1    No  Null  001  Paneer Biryani   100 

coupon_applied coupon_type  dish_id dish_name  dish_price 
0  Yes  Rs 40 off  002  Mutton Biryani  130 
1  No   Null  004  Aaloo tikki   95 


coupon_applied coupon_type dish_id dish_name  dish_price 
0  Yes   Rs 20 off  005  Sandwitch   50 
1  No    Null  006  Chicken Hundi  125 

而且我想在下面的格式輸出..

coupon_applied coupon_type dish_id  dish_name  dish_price 
0  Yes   Rs 20 off  001  Chicken Biryani  120 
1  No    Null   001  Paneer Biryani  100 
2  Yes   Rs 40 off  002  Mutton Biryani  130 
3  No    Null   004  Aaloo tikki   95 
4  Yes   Rs 20 off  005  Sandwitch   50 
5  No    Null   006  Chicken Hundi  125 

你能幫助我嗎?在此先感謝:)

+0

爲什麼不直接從mangoDB數據創建'pd.DataFrame()'? –

+0

請考慮給我們一個完整的數據框樣本,以便重現問題。 –

回答

2

dishes = [json_normalize(d) for d in df['dish']] 
df = pd.concat(dishes, ignore_index=True) 
+0

這些不是3個不同的數據幀,它的一個數據幀即由json_normalize函數返回。 – Neil

+0

謝謝..它的工作:) – Neil

+0

不客氣。 – Stefan

0

你應該能夠獲取列表dataframes的列表,然後CONCAT他們。

Inizialize一個新的數據框:

df = pd.DataFrame() 

創建Dataframes的空列表:

dflist = [] 

環路和追加dataframes

for i in range(0,len(df.dish)): 
    data_dish = json_normalize(df['dish'][i]) 
    dflist.append(data_dish) 

然後CONCAT列表進入全面數據幀:

df = pd.concat(dflist, ignore_index=True) 
+0

你的rpl的thnks。它正確添加索引。但同一個數據幀重複3次。 – Neil

+0

@ user2927983是的,也許嘗試更改循環的索引,如在其他答案中報告的那樣。 –

相關問題