如何按时间顺序排列月份?

2024-05-29 04:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

每个人都可以在X轴上看到,月份的顺序是随机的,但是我想按时间顺序排列月份,从1月到12月。谢谢你的回答

**#Counting the number of guests in both resort and city hotels**

Resort_Guests_Monhtly = Rh.groupby("arrival_date_month")["hotel"].count()
City_Guests_Monthly = Ch.groupby("arrival_date_month")["hotel"].count()

Resort_Guests_data = pd.DataFrame({"month":list(Resort_Guests_Monhtly.index), 
                               "hotel":"Resort hotel",
                               "guests":list(Resort_Guests_Monhtly.values)})

City_Guests_data = pd.DataFrame({"month":list(City_Guests_Monthly.index), 
                               "hotel":"City Hotel",
                               "guests":list(City_Guests_Monthly.values)}) function

**#Concenate the city and resort hotel data** 

all_guests_data =pd.concat([Resort_Guests_data,City_Guests_data],ignore_index=True)

**#Trying to order the months but didn't work** 

ordered_months = ["January", "February", "March", "April", "May", "June", 
      "July", "August", "September", "October", "November", "December"]
all_guests_data['month'] = pd.Categorical(all_guests_data['month'], categories=ordered_months, ordered=True)


 **#Visulization**

fig = px.line(all_guests_data, x="month" , y="guests",title="Average number of hotel guests per month", color='hotel')
fig.show()

Tags: thecitydataindexallhotellistpd
1条回答
网友
1楼 · 发布于 2024-05-29 04:27:03

如果我们着手解决x轴顺序,我们可以将此问题视为根据ordered_months列表对列month上的数据帧all_guests_data中的数据进行排序

因此,我们在**#Visulization**之前添加以下两行

all_guests_data['to_sort']=all_guests_data['month'].apply(lambda x:ordered_months.index(x))
all_guests_data = all_guests_data.sort_values('to_sort')

澄清示例

import plotly.express as px
import pandas as pd

# initializing data with monthes that are not in the correct order with acompanied with the given values
data={'month':["May", "June","July", "August", "September", "October", "November", "December","January", "February", "March", "April"],
      'guests':[50,60,70,80,90,100,110,120,10,20,30,40]}
all_guests_data = pd.DataFrame(data)

ordered_months = ["January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"]

# sorting data accoring to ordered_months
all_guests_data['to_sort']=all_guests_data['month'].apply(lambda x:ordered_months.index(x))
all_guests_data = all_guests_data.sort_values('to_sort')

# Visulization
fig = px.line(all_guests_data, x="month" , y="guests" )
fig.write_html('first_figure.html', auto_open=True)

相关问题 更多 >

    热门问题