
关于Excel的一些基本操作,对应到pandas里应该如何实现呢?

我的python数据分析环境是Anaconda和Jupyter notebook。
Part 1 excel的创建和读取
1、创建
#导入pandas数据包
打开文件路径,可找到创建的excel以及内容

2、读取
#查看行列数
因为编程语言是从第0行(也就是excel的第一行)开始的,默认第0行当做header。所以,如果excel的header是在第二行的话,读取excel的时候,用下面的代码:
df
如果表格中没有header(ID、Nmame)的话
#第一种读取方法
查看列名时。会发现'ID'这一列从列名中消失,ID变成了索引(在DataFrame中index和columns是区分开的)
3、行、列、单元格
pandas的数组有Series和DataFrame
用序列Series来创建行or列。
- Series的属性:.index,.values, .name,.index.name
- dataframe 的属性:.columns, .index,.values
series和python里的字典{keys:values}数据结构很像,会把字典的keys转化为序列的index,values转换为序列的data,如何将dictionary转换成series的方法:
d
直接创建序列,series除了一组数据外还包括一组索引:
s1
如何将series创建行和列
- 若以List形式加入DataFrame, 則該Series是被當作DataFrame的row加入;
- 若以Dict形式加入DataFrame, 則該Series是被當作DataFrame的column加入。
s1
index,具有对齐的作用
s1
4、自动填充功能--数据区域读取和填充数字
这里的excel有空行和空列,如何读取呢?

import

使用read_excel的两个参数:skiprows和usecols
import

数据框中的每一列是series
print
Series中有一个函数是at,填充列【ID】
#在ID列的第一行填充一个数值


#从上面的代码可看出dtype的类型改为int出错,先转为换为str

查看数据类型
Books
为了方便,这里把数据类型都改为字符串
import
填充【InStore】列
for

填充列【Date】
from

5、填充日期序列(填数值,填文本,填日期)
给日期列逐一加一天
from

给年份逐一加1,timedeltah只能得出天以及天以下的时间。
from
给月份逐一加1(但只有12个月)
def

这里将填充结果保存在原excel中
#这里不生成索引

上面的填充都是直接先找到series的某一列再去改,也可以直接使用dataframe的at函数,如:
start
part 2 只需一行代码
1、函数填充、计算列
1.1计算Price的值
import

books
得到Price这一列的值

1.2[ListPrice]列的值+2
#方法1:
方法2 :运用到Series的apply函数
def
方法3:lambda函数
def
2、排序、多重排序
2.1按Price价格排序
#读取文件,设置列[ID]为索引

product

2.2 多重排序:先按Worthy排序再按Price排序
product
3、数据筛选、过滤
#帅选出年龄在18-30岁的学生

ps:在python中,选择【Age】这一列的方法,除了student['Age'],还可以使用student.Age
student
还可以用更高级的函数lambda函数,表达式为:lambda 函数名:函数体
#筛选出年龄在18-30岁且分数在85-100的学生
part 3 数据可视化
1、柱状图:bar
pandas的制图功能是构建在matplotlib(文件夹,packge)库上的,这里要使用的是他下班的pyplot模块。
import

图形的属性设置
#图形形状、颜色、标题

ps:pandas作图没有matplotlib那么灵活,接下来就学习如何使用matplotlib绘图
import

2、分组柱状图(深度优化)

student

这里旋转45°后的对其看起来挺奇怪的,可以给一个参数“HA”[Horizontal alignment must be one of ('center', 'right', 'left')]

student

3、叠加柱状图和水平柱状图
3.1叠加柱状图
import

可以加上plt.tight_layout()的效果:

排序:总量由高到低
df

3.2 水平柱状图
只需把df.plot.bar改为df.plot.barh(),ascending=False改为ascending=True就行了,horizontal(水平线的意思)
import

4、饼图
import

此时是逆时针的饼图,如何制作成顺时针呢?

5、折线区域图和叠加区域图
5.1折线区域图
excel制图如下所示

weeks

5.2 叠加区域图
weeks

5.3 可看出叠加柱状图和叠加区域图的区别:
weeks

6、散点图和直方图
6.1 散点图
homes

6.2直方图
看西雅图地区面积的房价分布情况
homes

7、密度图(density)
homes
万分之四到万分之五之间的概率能买到一个1250尺的房子。

以上展示了pandas和matplotlib的绘图功能,包括:
- 柱状图:bar(分组柱状图、叠加柱状图、水平柱状图)
- 饼图:pie
- 折线图:plot(折线区域图、叠加区域图)
- 散点图:scatter
- 直方图:hist(histogram)
- 密度图:kde
对于图形属性应多实践才能记得牢靠!!!

附上以上内容的学习视频,感兴趣的同学可以戳下面的链接。
Python数据分析-pandas玩转Excel - 网易云课堂