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设计】网站的支持!

相关文章

pandas 转换成行列表进行读取与Nan处理的方法

pandas中有时需要按行依次对.csv文件读取内容,那么如何进行呢? 我们来完整操作一遍,假设我们已经有了一个.csv文件。 # 1.导入包 import pandas as p...

Python3将数据保存为txt文件的方法

Python3将数据保存为txt文件的方法

Python3将数据保存为txt文件的方法,具体内容如下所示: f = open("data/model_Weight.txt",'a') #若文件不存在,系统自动创建。'a'表...

Pytorch实现的手写数字mnist识别功能完整示例

本文实例讲述了Pytorch实现的手写数字mnist识别功能。分享给大家供大家参考,具体如下: import torch import torchvision as tv impor...

Python利用正则表达式实现计算器算法思路解析

  (1)不使用eval()等系统自带的计算方法   (2)实现四则混合运算、括号优先级解析 思路:   1、字符串预处理,将所有空格去除   2、判断是否存在括号运算,若存在进行第3步...

Linux下Python安装完成后使用pip命令的详细教程

Linux下Python安装完成后使用pip命令的详细教程

一、很多读者Python安装完成之后,想要下载相关的包,例如:numpy、pandas等Python中这些基础的包,但是,发现pip根本用不了,主要表现在一下几种情况: 二、出现这种情...