[英]Convert a Pandas Dataframe in Python list
我在熊貓中有這個數據框。
course = Courses.objects.filter(date__date__gte=dateFrom.date(),date__date__lte=dateTo.date()).values('course','price','date')
df_course = pd.DataFrame(course)
df_course['day_of_year'] = df_course.formatted_date.apply(lambda x: x.dayofyear)
dailyMinPrices = df_course.groupby(['hotel', 'day_of_year'])['price'].min()
它返回:
Course day_of_year Price
Course 1 154 70.0
155 74.0
156 85.0
157 90.0
158 83.0
159 79.0
160 81.0
161 75.0
162 113.0
163 85.0
164 83.0
Course 2 154 96.0
155 112.0
156 73.0
157 78.0
Course 3 154 99.0
155 74.0
156 78.0
157 70.0
158 94.0
159 82.0
我正在嘗試將其轉換為 django list 或 django dict,但它總是返回:
"dailyMinPrices": [70.0,74.0,85.0,90.0,83.0, 79.0,81.0,75.0,113.0,85.0]
我正在嘗試獲得這種結構:
"dailyMinPrices": {'course 1':{['day_of_year':154,'price':70.0], ['day_of_year':154,'price':70.0],['day_of_year':154,'price':70.0]}, 'course 2':{...},'course 3':{...}}
我正在嘗試:
dailyMinPrices.values.tolist() #Not working
dailyMinPrices.to_dict(), Return errors
我想不使用 for,因為它有很多寄存器。
to_dict(orient='records')
接近預期結果。 但是因為你想要一個分層的字典,你應該首先使用groupby
在第一級索引上拆分數據幀。 使用您的樣本數據,
{i[0]: i[1].reset_index(level=1).to_dict(orient='records')
for i in df.groupby(level=0)}
按預期給出(使用pprint
):
{'Course 1': [{'Price': 70.0, 'day_of_year': 154},
{'Price': 74.0, 'day_of_year': 155},
{'Price': 85.0, 'day_of_year': 156},
{'Price': 90.0, 'day_of_year': 157},
{'Price': 83.0, 'day_of_year': 158},
{'Price': 79.0, 'day_of_year': 159},
{'Price': 81.0, 'day_of_year': 160},
{'Price': 75.0, 'day_of_year': 161},
{'Price': 113.0, 'day_of_year': 162},
{'Price': 85.0, 'day_of_year': 163},
{'Price': 83.0, 'day_of_year': 164}],
'Course 2': [{'Price': 96.0, 'day_of_year': 154},
{'Price': 112.0, 'day_of_year': 155},
{'Price': 73.0, 'day_of_year': 156},
{'Price': 78.0, 'day_of_year': 157}],
'Course 3': [{'Price': 99.0, 'day_of_year': 154},
{'Price': 74.0, 'day_of_year': 155},
{'Price': 78.0, 'day_of_year': 156},
{'Price': 70.0, 'day_of_year': 157},
{'Price': 94.0, 'day_of_year': 158},
{'Price': 82.0, 'day_of_year': 159}]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.