pandas 按照特定顺序输出的实现代码

yipeiwu_com6年前Python基础

df.groupby() 之后按照特定顺序输出,方便后续作图,或者跟其他df对比作图。

## 构造 pd.DataFrame
patient_id = ['71835318256532',
 '87791375711',
 '66979212649388',
 '46569922967175',
 '998612492555522',
 '982293214194',
 '89981833848',
 '17912315786975',
 '4683495482494',
 '1484143378533',
 '56866972273357',
 '7796319285658',
 '414462476158336',
 '449519578512573',
 '61826664459895']
week = ['tuesday',
 'tuesday',
 'wednesday',
 'monday',
 'tuesday',
 'monday',
 'friday',
 'tuesday',
 'monday',
 'friday',
 'saturday',
 'thursday',
 'wednesday',
 'thursday',
 'wednesday']
d = {'patient_id': patient_id, 'week':week}
test = pd.DataFrame(data=d)
## 聚类计数
test.groupby('week')['patient_id'].count()
## output
week
friday  2
monday  3
saturday  1
thursday  2
tuesday  4
wednesday 3
Name: patient_id, dtype: int64
## 按照特定顺序输出
ind = ['monday','tuesday','wednesday','thursday','friday','saturday']
test.groupby('week')['patient_id'].count()[ind]
## output
week
monday  3
tuesday  4
wednesday 3
thursday  2
friday  2
saturday  1
Name: patient_id, dtype: int64

作图效果如下

test.groupby('week')['patient_id'].count().plot(kind='bar');

这里写图片描述

ind = ['monday','tuesday','wednesday','thursday','friday','saturday']
test.groupby('week')['patient_id'].count()[ind].plot(kind='bar');

这里写图片描述

总结

以上所述是小编给大家介绍的pandas 按照特定顺序输出的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python Subprocess模块原理及实例

Python Subprocess模块原理及实例

前言 其实有一个模块也支持执行系统命令,那个模块就是sys.system,但他执行系统命令会直接通过主进程去执行命令,那假如,该命令的执行需要耗费一个小时,那么主进程会卡一个小时,而不...

解决python3运行selenium下HTMLTestRunner报错的问题

修改HTMLTestRunner.py以支持python3+ 搜索到的结果整理 修改一: 在python shell里输入 >>>import HTMLTestRunn...

python、PyTorch图像读取与numpy转换实例

Tensor转为numpy np.array(Tensor) numpy转换为Tensor torch.Tensor(numpy.darray) PIL.Image.Image转换成nu...

Pycharm设置utf-8自动显示方法

如下所示: File->Setting->Editor->File and Code Templates->python script,右侧框框内输入: ...

使用Python正则表达式操作文本数据的方法

什么是正则表达式 正则表达式,是简单地字符的序列,可指定特定的搜索模式。正则表达式已存在很长一段时间,并且它本身就是计算机科学的一个领域。 在 Python中,使用Python的内置r...