gpt4 book ai didi

python - 如何在 pandas 中连接数据框?

转载 作者:行者123 更新时间:2023-12-01 04:18:01 25 4
gpt4 key购买 nike

我通过 pymongo 将数据从 mongoDB 获取到 python,然后将其转换为 pandas dataframe

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

你能帮我解决这个问题吗?预先感谢:)

最佳答案

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

关于python - 如何在 pandas 中连接数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com