[英]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.