python - 在 Pandas 中排列字符串 Month 行的最简单方法是什么
问题描述
我有一个带有月份列的df,它是字符串:
Month Value Details
January 10 H12
April 12 J11
June 13 K03
May 08 Y21
April to March
我需要从模型中安排月份。哪种方法最简单?期望的结果:
Month Value Details
April 12 J11
May 08 Y21
June 13 K03
January 10 H12
解决方案
如果需要在字典列表中缺少某些月份和所有月份的情况下正常工作的解决方案,请使用Series.map
以下Series.argsort
命令更改顺序DataFrame.iloc
:
d = {'April':1,'May':2,'June':3,'July':4,'January':12}
df = df.iloc[df['Month'].map(d).argsort()]
print (df)
Month Value Details
1 April 12 J11
3 May 8 Y21
2 June 13 K03
0 January 10 H12
或使用有序分类:
#add another months
c = ['April','May','June','July','January']
df['Month'] = pd.Categorical(df['Month'], categories=c, ordered=True)
df = df.sort_values('Month')
print (df)
Month Value Details
1 April 12 J11
3 May 8 Y21
2 June 13 K03
0 January 10 H12
推荐阅读
- javascript - 使用 Javascript 的 Hill Cipher Encryption 错误
- java - Which datastore to use when you have unbounded(dynamic) number of fields/attributes for an entity?
- c++ - 如何在向量字符串中搜索元素?
- python - 如何相互减去所有日期列(以排列方式)并将它们存储在新的 pandas DataFrame 中?
- ember.js - 在没有 ember-cli 的情况下运行 ember 需要哪些东西?
- django - Django REST:POST 请求问题,必填字段
- mongodb - mongoDB 日志中出现未经授权的错误
- azure - Azure EventGrid 在哪里保留等待传递的消息?
- angularjs - AngularJS v1.8.0 ng-selected 选项不起作用
- javascript - 为什么 $.get 总是以空警报的形式出现?