如何对Python绘制的911呼叫月度数据图表进行数值排序?
如何对911呼叫数据的月度统计图表进行排序?
嘿,我来帮你搞定这个问题!你现在的代码里,value_counts()默认是按呼叫数量的高低排序的,不是按时间顺序排列月份,所以图表的x轴才会显得杂乱。下面给你两种解决思路,推荐第二种更可靠的方案:
方法一:对现有字符串格式的年月索引重新排序
如果你想保留自己拼接的YYYY-MM字符串格式,可以先把索引转换成时间类型,排序后再转回字符串:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('911_calls_for_service.csv') df['callDateTime'] = pd.to_datetime(df['callDateTime']) # 保留你原来的年月拼接方式 df['MonthYear'] = df['callDateTime'].apply(lambda time: f"{time.year}-{time.month}") # 获取计数后,将索引转为datetime类型排序 counts = df['MonthYear'].value_counts() counts.index = pd.to_datetime(counts.index) counts = counts.sort_index() # 转回字符串格式的索引(可选,不转也能正常绘图) counts.index = counts.index.strftime('%Y-%m') # 绘图和输出 counts.plot() print(counts) plt.tight_layout() plt.show()
方法二:用Pandas内置的时间周期类型(推荐)
自己拼接字符串容易出现月份是一位数时的排序bug(比如2023-10字符串排序会跑到2023-9前面),用dt.to_period('M')生成的是专门的时间周期类型,天然支持正确的时间排序:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('911_calls_for_service.csv') df['callDateTime'] = pd.to_datetime(df['callDateTime']) # 生成规范的年月周期类型 df['MonthYear'] = df['callDateTime'].dt.to_period('M') # 按年月分组计数,直接按索引(时间顺序)排序 monthly_counts = df.groupby('MonthYear').size().sort_index() # 绘图和输出 monthly_counts.plot() print(monthly_counts) plt.tight_layout() plt.show()
这样生成的图表x轴就会严格按照从早到晚的时间顺序排列啦!
内容的提问来源于stack exchange,提问作者Techie Boy
相关产品推荐
相关产品推荐

