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

Python 如何按时间顺序排列月份?,python,plotly,Python,Plotly,每个人都可以在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(&quo


每个人都可以在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()

如果我们着手解决x轴顺序问题,我们可以将此问题视为根据
ordered\u months
列表对列
month
上的DataFrame
all\u guests\u data
中的数据进行排序

因此,我们在
**#Visualization**

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')
澄清示例


“在X轴上,月份的顺序是随机的”——不是随机的,而是按字母顺序排列的。@JustinEzequiel事实上你是对的,有没有办法把它改为按时间顺序排列的?用1-12作为xaxis值,并用Jan-Dec作为xaxis标签来掩盖它。@Soleil MathieuPrévot:你为什么认为这不能回答这个问题?我不确定这是不是一个正确的答案,但这就是投票的目的。@Nour Allah Hussein它工作得很好,非常感谢!!
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)