【发布时间】:2016-03-09 13:29:20
【问题描述】:
我通过 pymongo 从 mongoDB 获取数据到 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
你能帮我解决这个问题吗?在此先感谢:)
【问题讨论】:
-
你为什么不直接从mangoDB数据创建
pd.DataFrame()? -
请考虑向我们提供数据帧的完整样本,以便重现问题。
标签: python json mongodb pandas