目录
1. 使用方法说明
2. Python编程核心
2.1 基本运算符
2.1.1 算数运算符
(1)加法
(2)减法
(3)乘法
(4)除法
(5)取余数
(6)整数除法
(7)乘方
(8)指数运算
(9)对数运算
2.1.2 比较运算符
(10)小于
(11)小于等于
(12)大于
(13)大于等于
(14)相等
(15)不等
2.1.3 逻辑运算
(16)逻辑且
(17)逻辑或
(18)逻辑非
2.1.4 变量赋值与使用
(19)等号赋值
(20)被赋值变量使用
2.2 基本数据类型操作
2.2.1 字符串操作
(21)字符串创建1
(22)字符串创建
(23)字符串索引
(24)字符串切片
(25)字符串合并1
(26)字符串合并2
(27)字符串去掉首尾特殊字符
(28)字符串拆分
(29)字符串内查找子字符串1
(30)字符串内查找子字符串2
(31)子字符串替换
2.2.2 元组操作
(32)创建元组
(33)元组解包
2.2.3 列表操作
(34)创建列表
(35)列表索引
(36)列表切片
(37)列表添加值
(38)列表添加多个值
(39)列表指定位置添加值
(40)列表删除元素1
(41)列表删除元素2
2.2.4 字典操作
(42)创建字典
(43)字典中获取值1
(44)字典中获取值2
(45)字典中删除某映射
(46)获取字典的键
(47)获取字典的值
(48)获取字典的键值组合
2.3 控制结构
2.3.1 分支结构
(49)分支结构if
2.3.2 循环结构
(50)循环结构while
(51)循环结构for
2.3.3 终止循环
(52)break语句
(53)continue语句
2.4 异常处理
(54)异常处理结构
2.5 函数
2.5.1 自定义函数
(55)函数定义
(56)匿名函数 lambda
(57)函数调用
2.5.1 内置函数
(58)转化为列表list
(59)转化为字典dict
(60)转化为字符串str
(61)转化为整数int
(62)转化为浮点数float
(63)print
(64)获得对象长度 len
(65)获得循环用等差数列 range
(66)反转可迭代对象顺序
(67)排序 sorted
(68)并列读取 zip
(69)可替代循环的方法 map
(70)筛选 filter
(71)列表解析式
(72)打开文件open函数
2.6 类
(73)类定义
(74)创建实例
(75)属性调用(类或实例)
(76)方法调用
3 NumPy
3.1 模块导入
(77)导入numpy模块
3.2 数据创建
3.2.1 常规创建方式
(78)np.array()函数
(79)np.arange()函数
3.2.2 创建特殊ndarray
(80)np.zeros
(81)np.ones
(82)np.random模块
3.3 数学运算
3.3.1 基本运算
(83)求绝对值
(84)求平方根
(85)求指数幂
(86)求自然对数
(87)返回符号
3.3.2 聚合运算
(88)求最大值
(89)求最大值索引
(90)求最小值
(91)求最小值索引
(92)求和
(93)求积
(94)求均值
(95)求中位数
(96)求标准差
(97)求方差
3.3.3 累计运算
(98)累计和
(99)累积乘积
3.3.4 逻辑运算
(100)逻辑且1
(101)逻辑或1
(102)逻辑且2
(103)逻辑或2
(104)np.where
(105)广播
3.4 数据操作
3.4.1 索引
(106)位置索引
(107)bool值索引
3.4.2 数据规整化
(108)排序
(109)维度调整
(110)转置
(111)拼接
4 Pandas
4.1 模块导入
(112)导入pandas模块
4.2 Series数据创建
(113)创建Series1
(114)创建Series2
(115)创建DataFrame
4.2 数据操作
4.2.1 Series索引
(116)获取 Series 的 index
(117)获取 Series 的 value
(118)修改 Series 索引
(119)Series以位置进行索引
(120)Series以index进行索引
(121)Series以bool值进行索引
(122)Series以位置进行切片
(123)Series以index进行切片
4.2.2 DataFrame索引
(124)获得DataFrame行index
(125)获得DataFrame列index(列名)
(126)修改行index
(127)DataFrame获取列数据
(128)DataFrame获取多列数据
(129)DataFrame获取行数据1
(130)DataFrame获取行数据2
(131)DataFrame获取多行数据1
(132)DataFrame获取多行数据2
(133)以行列 index 获取某个位置数据
(134)以行列位置获取某个位置数据
(135)以行列 index 获取某个区域数据
(136)以行列位置获取某个区域数据
(137)DataFrame获得前 n 行数据
(138)DataFrame获得末尾 n行数据
4.2.3 Series数据清洗、排序、平移、拼接
(139)Series检测缺失值
(140)Series填充缺失值
(141)Series删除缺失值
(142)Series以 index 排序
(143)Series以值进行排序
(144)Series值平移
(145)Series拼接
4.2.4 DataFrame数据清洗、排序、平移、拼接
(146)DataFrame检测缺失值
(147)DataFrame填充缺失值
(148)DataFrame删除缺失值
(149)DataFrame以index进行排序
(150)DataFrame以某值进行排序
(151)Dataframe与Series合并简单方式。
(152)两个DataFrame进行合并1
(153)两个DataFrame进行合并2
(154)两个DataFrame进行拼接
4.3 数据统计
4.3.1 Series相关计算
(155)Series汇总统计
(156)Series统计非NaN值数量
(157)Series统计最大值
(158)Series统计最小值
(159)Series获得最大值索引
(160)Series获得最小值索引
(161)Series获得分位数
(162)Series获得总和
(163)Series获得平均值
(164)Series获得算数中位数
(165)Series获得平均绝对离差
(166)Series获得方差
(167)Series获得标准差
(168)Series获得偏度
(169)Series获得峰度
(170)Series获得累计和
(171)Series获得累计最大值
(172)Series获取累计最小值
(173)Series获取累计乘积
(174)Series计算一阶差分
(175)Series计算百分数变化
(176)计算两个series协方差
(177)计算两个Series相关系数
(178)Series移动窗口函数使用1
(179)Series移动窗口函数使用2
4.3.2 DataFrame相关计算
(180)DataFrame汇总统计
(181)DataFrame统计非NaN值数量
(182)DataFrame统计最大值
(183)DataFrame统计最小值
(184)DataFrame获得分位数
(185)DataFrame获得总和
(186)DataFrame获得平均值
(187)DataFrame获得算数中位数
(188)DataFrame获得平均绝对离差
(189)DataFrame获得方差
(190)DataFrame获得标准差
(191)DataFrame获得偏度
(192)DataFrame获得峰度
(193)DataFrame获得累计和
(194)DataFrame获得累计最大值
(195)DataFrame获取累计最小值
(196)DataFrame获取累计乘积
(197)DataFrame计算百分数变化
(198)DataFrame计算各列协方差矩阵
(199)DataFrame计算各列相关系数矩阵
(200)DataFrame各列分别计算与一个Series之间的相关系数
(201)DataFrame移动窗口函数1
(202)DataFrame移动窗口函数1
(203)DataFrame的Groupby技术1
(204)DataFrame的Groupby技术1
4.4 时间序列处理
(205)日期字符串转化为datetime
(206)生成指定DatetimeIndex
(207)生成指定PeriodIndex
(208)时间序列索引
(209)转换时间序列频率
4.5 数据读取与储存
(210)csv文件读取
(211)excel文件读取
(212)储存为csv文件
(213)储存为excel文件
##################################
1. 使用方法说明
手册内容分为python编程核心、Numpy、Pandas三大部分。
手册编写时使用python及相关模块版本:
- python:python3.6.1
- numpy:numpy1.13.3
- pandas: pandas0.20.3
In [6]:
7 // 4 # 整数除法,返回不大于结果的一个最大的整数
In [8]:
import math
math.exp(3) # 返回输入数字的指数
In [9]:
import math
math.log(10) # 取自然对数
(23)字符串索引
通过位置获得字符串中某个字符。
索引位置为正表示从左向右寻找字符,索引位置为负表示从右向左寻找字符。
In [23]:
st = 'Hello, World!' # 创建字符串
st[2] # 进行索引,获取位置为2的字符,对应字母'l'
(24)字符串切片
通过位置获取字符串中某个子字符串。
string[a:b]表示获取从位置a开始到位置b为止之间的子字符串。
string[a:] 表示获取从位置a开始到字符串末尾所有字符的子字符串。
string[:b] 表示获取从字符串开头到位置b为止之间所有字符的子字符串。
string[:] 表示复制原字符串。
In [24]:
st = 'Hello, World!' # 创建字符串
st[2 : 4] # 进行索引
(25)字符串合并1
使用'+'号将多个字符串合并成1个字符串
In [25]:
'Hello '+'World' + ' and Python!'
Out[25]:
'Hello World and Python!'
(26)字符串合并2
通过字符串'join'方法使用指定字符串连接多个字符串成一个字符串。
In [26]:
'##'.join(['Hello', 'World'])
(27)字符串去掉首尾特殊字符
通过字符串'strip'方法去掉字符串首尾特殊字符,默认去除'\n'。
通过open函数打开并读取文件时常用。
In [27]:
'\nHello world\n'.strip()
通过字符串'split'方法根据某一字符对字符串进行拆分,并以字符串组成的列表形式返回。分隔用字符默认为'\t'。
通过open函数打开并读取文件时常用。
通过字符串'find'方法获得子字符串首次出现在字符串中的位置,如果未发现将返回-1。
(30)字符串内查找子字符串2
通过'in'判断小字符串是否为大字符串的子字符串,返回bool值。
In [30]:
'Hello' in 'Hello, world!'
通过字符串'replace'方法将子字符串替代为新字符串,返回完成替代后的新字符串。
In [31]:
'Hello! world!'.replace('!', '!!!')
In [33]:
a, b, c = (1, 2, 3) # 元组解包
print(a, b, c) # 打印被赋值变量名
(34)创建列表
注意,以下字母l均为字母L的小写
(35)列表索引
通过位置获得列表中某个元素。
索引位置为正表示从左向右寻找元素,索引位置为负表示从右向左寻找元素。
In [35]:
l = [1, 2, 3, 4] # 创建列表并赋值给变量名l
l[2] # 进行列表索引
(36)列表切片
通过位置获取列表某个子列表。
list[a:b]表示获取从位置a开始到位置b为止之间的子列表,不含b位置元素。
list[a:] 表示获取从位置a开始到列表末尾所有元素的子列表。
list[:b] 表示获取从列表开头到位置b为止之间所有元素的子列表,不含b位置元素。
list[a:b:s]表示以步长为s获取从位置a开始到位置b为止之间的子列表,不含b位置元素。
list[:] 表示复制原列表。
In [36]:
l = [1, 2, 3, 4, 5, 6] # 创建列表并赋值给变量名l
l[1:5] # 进行列表切片
(37)列表添加值
通过列表'append'方法在列表末尾添加一个元素。
In [37]:
l = [1, 2, 3, 4] # 创建列表并赋值给变量名l
l.append(5) # 列表末尾添加一个值
l
(38)列表添加多个值
通过列表'extend'方法在列表末尾添加多个值。
In [38]:
l = [1, 2, 3, 4] # 创建列表并赋值给变量名l
l.extend((111, 111)) # 列表末尾添加多个值
l
(39)列表指定位置添加值
通过列表'insert'方法在列表指定位置添加某一个元素。
In [39]:
l = [1, 2, 3, 4] # 创建列表并赋值给变量名l
l.insert(2, 'insert') # 列表指定位置添加一个值
l
(40)列表删除元素1
通过列表'remove'方法根据元素的值进行删除。
In [40]:
l = [1, 2, 'insert', 3, 4] # 创建列表并赋值给变量名l
l.remove('insert') # 从列表删除某值
l
(41)列表删除元素2
根据列表索引或切片使用'del'对列表中元素进行删除。可同时删除多个值。
In [41]:
l = [1, 2, 3, 4] # 创建列表并赋值给变量名l
del l[0:2] # 从列表中删除元素
l
In [42]:
dictionary = {'a':1 , 'b':2, 'c':3}
In [43]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
dictionary['a'] # 用key从字典中获取值
(44)字典中获取值2
根据键使用字典'get'方法获取字典中相应值。若key不存在,返回第二个参数对应的值。
In [44]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
dictionary.get('d', 100) # 用key从字典中获取值
(45)字典中删除某映射
使用'del'删除映射。
In [45]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
del dictionary['a'] # 删除映射
(46)获取字典的键
通过字典'keys'方法获得一个可以获取字典键的迭代器。
在循环中经常使用。
In [47]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
dictionary.keys() # 获得字典键
Out[47]:
dict_keys(['a', 'b', 'c'])
(47)获取字典的值
通过字典'values'方法获得一个可以获取字典值的迭代器。
In [48]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
dictionary.values() # 获得字典值
(48)获取字典的键值组合
通过字典'items'函数获得一个可以获得字典键值组合的迭代器。
在循环中经常使用。
In [49]:
dictionary = {'a':1 , 'b':2, 'c':3} # 创建字典并赋值给dictionary
dictionary.items() # 获取键值组合
Out[49]:
dict_items([('a', 1), ('b', 2), ('c', 3)])
(49)分支结构if
if condition1:
...
elif condition2:
...
elif condition 3:
...
else:
...
if判断从上到下运行,当遇到第一个满足条件的判断将执行该条件下相应程序后退出if结构。
In [50]:
if 3 > 2: # 第一个条件满足,则运行该条件下的print后直接退出if结构
print('3 > 2')
elif 4 > 2:
print('4 > 2')
else:
print('3 < 2')
(50)循环结构while
while condition:
...
运行时将不断执行循环内代码,直到condition条件为False或通过break终止循环。
In [51]:
i = 0
while i < 4: # 当循环4次后,第五次i为4,条件不满足则跳出循环。
print(i)
i += 1
(51)循环结构for
for i in iterable:
...
运行时每次从可迭代对象中获得一个值,然后执行一次循环中代码,直到可迭代对象循环完或break终止循环。
In [52]:
for i in range(4):
print(i)
(52)break语句
用于强制停止循环,然后退出循环。
(53)continue语句
用于循环中跳过本次循环内continue后代码的执行,直接进行下一次代码执行。
(54)异常处理结构
try:
...
except ... :
...
except ... :
...
else:
...
finally:
...
将需要监控异常的代码放在try下的代码块。
当try下代码块执行发生异常时,通过except捕捉异常,然后执行该except捕捉异常下的代码。except可有多个,如果except未捕捉到特定异常,则报错。
当try下代码块没有异常发生时,那么运行else下代码块。else下代码块只有在没有异常发生时才会运行。
无论try下代码块有无异常发生,都会运行finally下代码块
In [53]:
import math
i = 10
try:
print("square root of %d is %f" % (i, math.sqrt(i)))
except ValueError:
print("cannot calculate square root of %d" % i)
except TypeError:
print("the input '%s' is not a number" % i)
else:
print("simply continuing the iteration")
finally: # finally是不管程序是否出错最终都会执行;
print("I am executed not matter what\n")
square root of 10 is 3.162278
simply continuing the iteration
I am executed not matter what
(55)函数定义
通过def创建一个函数对象并赋值给一个变量名。
In [54]:
def my_function(*args, **kwargs):
print(*args)
print(dict(kwargs))
return None
(56)匿名函数 lambda
通过lambda定义一个简单函数。一般使用时作为参数传入其他函数使用。
Out[55]:
<function __main__.<lambda>>
(57)函数调用
(所有函数,无论内置还是自定义,调用方法一致)
对于无参数函数,在函数名后添加括号完成函数调用。
对于有参数函数,在函数名后括号内通过位置或关键字传递参数,然后完成函数调用。
In [56]:
def my_square(n): # 定义一个函数
return n**2
my_square(10) # 完成函数调用
(58)转化为列表list
将可迭代对象转化为list
(59)转化为字典dict
将可提供成对数据的对象转化为字典。
In [58]:
a = [('a',1), ('b', 2)] # 列表a中的每一个元素都是一个包含两个元素的元组
dict(a) # 构建字典
In [59]:
a = 1234
str(a) # 将整数a转化为字符串
In [60]:
a = 23.23
int(a) # 将浮点数a转化为整数
In [61]:
a = '23.23'
float(a) # 将字符串a转化为浮点数
(63)print
显示传入对象。对于被赋值的变量名查看赋值对象使用print函数,该函数非常常用。
(64)获得对象长度 len
对于列表、元组、ndarray等对象都有数据长度,具体含义有数据类型决定。
该函数经常在循环中与range配合使用。
(65)获得循环用等差数列 range
返回一个迭代器。
range(n)返回一个可产生从0到n(不含n),步长为1数字的迭代器。
range(a, b, s)返回一个可产生从a到b(不含b),步长为s数字的迭代器。
该函数经常在for循环中使用。
In [65]:
for i in range(4):
print(i)
(66)反转可迭代对象顺序
使用reversed函数将对象中元素顺序反转,返回一个可提供顺序反转后的迭代器。
该函数经常在循环中使用
In [66]:
a = [1, 2, 3, 4] # 创建一个列表并赋值给变量名a
reversed(a) # 顺序反转
Out[66]:
<list_reverseiterator at 0x824cf60>
In [67]:
for i in reversed(a):
print(i)
(67)排序 sorted
使用sorted函数将对象中的元素排序后以列表形式返回。
In [68]:
a = [1, 3, 2, 4] # 创建一个列表并赋值给变量名a
sorted(a) # 排序
(68)并列读取 zip
使用zip函数并列读取多个可迭代对象,返回数据重新组合后的迭代器。
经常在循环中使用。
In [69]:
a = [1, 2, 3, 4] # 创建一个列表并赋值给变量名a
b = [4, 3, 2, 1] # 创建一个列表并赋值给变量名b
zip(a, b) # 重新组合
In [70]:
for item in zip(a,b):
print(item)
(1, 4)
(2, 3)
(3, 2)
(4, 1)
(69)可替代循环的方法 map
map(func, *iterables)运行时将函数应用于可迭代对象中的每一个元素。如果func后的可迭代对象有多个,那么会以并行方式将可迭代对象的元素传入func函数。
返回一个可迭代对象。
In [72]:
list(map(abs, [1, -2, 3, -4]))
(70)筛选 filter
对可迭代对象中元素按照传入标准进行筛选,如果满足条件(即经传入筛选标判断后返回True),则保留该元素。
返回可执行筛选的迭代器。
In [73]:
a = filter(lambda x: x>2, [1, -2, 3, 4])
a
(71)列表解析式
类似for循环,但运行速度更快。最后生成列表。
(73)类定义
使用class语句对类进行定义。其中,可以完成类属性、类方法的定义。
In [76]:
class test():
name = 'name' # 定义类属性name
def __init__(self, age): # 通过定义__init__函数,可以在创建实例时自动运行
self.age = age # 定义实例的属性
def show_age(self): # 定义类方法
print('age is ',self.age)
(74)创建实例
如果创建实例时不需要参数,则通过在类名称后面加括号完成一个实例的创建。
如果创建实例需要参数,则需要在类名称后面的括号内通过位置或关键字传递参数的方式完成实例创建。
In [77]:
class test(): # 定义类
pass
instance = test() # 创建实例
Out[78]:
<__main__.test at 0x82296d8>
(75)属性调用(类或实例)
对于类或实例,都可以通过'.attribute'方式获取相应属性。
In [79]:
class test(): # 定义类
age=9
test.age # 调用类属性
(76)方法调用
对于类或实例,都可以通过'.method(*args, **kwargs)'方式完成方法调用。
In [80]:
class test(): # 定义类
def my_print(self): # 定义实例方法
print('myself')
instance = test() # 创建实例
instance.my_print() # 调用示例方法(从类中继承)
(77)导入numpy模块
使用import语句导入numpy模块。
下句为导入numpy模块代码惯例。
(78)np.array()函数
使用numpy中array函数将可迭代对象转化为ndarray类型以备后续计算。
In [82]:
a = np.array(range(4)) # 生成ndarray
a
(79)np.arange()函数
使用numpy中arange函数直接生成ndarray数据,运算逻辑类似range()内置函数。
np.arange(n)返回一个可产生从0到n(不含n),步长为1数字的ndarray.
np.arange(a, b, s)返回一个可产生从a到b(不含b),步长为s数字的ndarray.
(80)np.zeros
生成一个形状如传入参数,元素均为0的ndarray。
Out[84]:
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
(81)np.ones
生成一个形状如传入参数,元素均为1的ndarray。
Out[85]:
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
(82)np.random模块
利用该模块内的函数生成形状如传入参数,元素符合对应分布的ndarray。
常用np.random.randn(a)生成a*1的ndarray,其值符合正态分布。
(该模块内其他函数可在ipython中运行dir(np.random)进行查看)
Out[86]:
array([ 0.87057995, 1.6873523 , 0.54767621])
3.3 数学运算
3.3.1 基本运算
(83)求绝对值
使用np.abs函数对ndarray中每一个元素求绝对值。
In [87]:
a = np.array([1, -2, 3, -4]) # 创建ndarray
np.abs(a) # 求绝对值
(84)求平方根
使用np.sqrt函数对ndarray中每个元素求平方根。
In [88]:
a = np.array([1, 2, 3, 4]) # 创建ndarray
np.sqrt(a) # 求平方根
Out[88]:
array([ 1. , 1.41421356, 1.73205081, 2. ])
(85)求指数幂
使用np.exp函数对ndarray中每个元素求指数幂
In [89]:
a = np.array([1, 2, 3, 4]) # 创建ndarray
np.exp(a) # 求指数幂
Out[89]:
array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003])
(86)求自然对数
使用np.log函数对ndarray中每个元素求自然对数。
In [90]:
a = np.array([1, 2, 3, 4]) # 创建ndarray
np.log(a) # 求自然对数
Out[90]:
array([ 0. , 0.69314718, 1.09861229, 1.38629436])
(87)返回符号
使用np.sign函数对ndarray中每个元素的符号进行判断。其中,对应正数返回1,对应负数返回-1,对应0返回0。
In [91]:
a = np.array([1, -2, 0]) # 创建ndarray
np.sign(a) # 求符号
(88)求最大值
np.max函数与array.max方法等价。
In [92]:
a = np.array([1, -2, 0]) # 创建ndarray
a.max() # 求最大值
(89)求最大值索引
返回ndarray元素中最大元素的位置索引。
np.argmax函数与array.argmax方法等价。
In [93]:
a = np.array([1, -2, 0]) # 创建ndarray
a.argmax() # 求最大值索引
(90)求最小值
np.min函数与array.min方法等价。
In [94]:
a = np.array([1, -2, 0]) # 创建ndarray
a.min() # 求最小值
(91)求最小值索引
np.argmin函数与array.argmin方法等价。
In [95]:
a = np.array([1, -2, 0]) # 创建ndarray
a.argmin() # 求最小值索引
(92)求和
np.sum函数与array.sum方法等价。
In [96]:
a = np.array([1, -2, 0]) # 创建ndarray
a.sum() # 求和
(93)求积
np.prod函数和array.prod方法等价。
In [97]:
a = np.array([1, -2, 0]) # 创建ndarray
a.prod() # 求积
(94)求均值
np.mean函数与array.mean方法等价。
In [98]:
a = np.array([1, -2, 0]) # 创建ndarray
a.mean() # 求均值
In [99]:
a = np.array([1, -2, 0]) # 创建ndarray
np.median(a) # 求中位数
(96)求标准差
返回沿特定轴的标准差。
np.std函数与array.std方法等价。
In [100]:
a = np.array([1, -2, 0]) # 创建ndarray
a.std() # 求标准差
(97)求方差
返回沿特定轴的方差。
np.var函数与array.var方法等价。
In [101]:
a = np.array([1, -2, 0]) # 创建ndarray
a.var() # 计算方差
(98)累计和
np.cumsum函数与array.cumsum方法等价。
In [102]:
a = np.array([1, -2, 0]) # 创建ndarray
a.cumsum() # 计算累计和
Out[102]:
array([ 1, -1, -1], dtype=int32)
(99)累积乘积
np.cumprod函数与array.cumprod方法等价。
In [103]:
a = np.array([1, -2, 0]) # 创建ndarray
a.cumprod() # 计算累计乘积
Out[103]:
array([ 1, -2, 0], dtype=int32)
(100)逻辑且1
如果ndarray中每一个元素都为True,则返回True。
np.all函数与array.all方法等价。
In [104]:
np.array([True, False, False]).all()
(101)逻辑或1
如果ndarray中有一个元素为True,则返回True。
np.any函数与array.any方法等价。
In [105]:
np.array([True, False, False]).any()
(102)逻辑且2
对多个ndarray中每一个元素进行并列判断,如果并列的每一个元素全为True,则返回True。
In [106]:
a = np.array([True, False, True, False]) # 创建ndarray a
b = np.array([False, True, True, False]) # 创建ndarray b
In [107]:
np.logical_and(a, b) # 进行逻辑且判断
Out[107]:
array([False, False, True, False], dtype=bool)
(103)逻辑或2
对多个ndarray中的每一个元素进行并列判断, 如果并列的元素有一个为True,则返回True。
In [108]:
a = np.array([True, False, True, False]) # 创建ndarray a
b = np.array([False, True, True, False]) # 创建ndarray b
Out[109]:
array([ True, True, True, False], dtype=bool)
(104)np.where
对ndarray中每一个元素进行判断,如果满足条件,对于该元素返回第二个参数,不满足返回第三个参数。最后返回结果为ndarray。
常用于对数据条件判断后替换为其他值。
In [110]:
a = np.array([True, False, True]) # 创建ndarray a
np.where(a, 1, 0)
(105)广播
(详见AQF课程numpy基础部分)
In [111]:
a = np.array([1, 3, 2, 4]) # 创建ndarray a
a + 2
(106)位置索引
根据位置获取ndarray的某一个值,使用方法类似list。
In [112]:
a = np.array([1,2,3,4]) # 创建ndarray
a[2] # 进行位置索引
(107)bool值索引
使用bool值进行索引,True则获取对应ndarray中的元素,False则不获取。最终返回ndarray。
In [113]:
a = np.array([1,2,3,4]) # 创建ndarray
a[[True, False, True, False]] # bool值索引
(108)排序
对ndarray中元素进行排序,默认为升序排列。
np.sort函数和array.sort方法类似。
In [115]:
a = np.array([1,2,3,4]) # 创建ndarray
a.sort() # 进行排序
a
(109)维度调整
对ndarray中元素进行维度调整,调整为输入参数形状。
np.reshape函数和array.reshape方法等价。
In [116]:
a = np.array([1,2,3,4]) # 创建ndarray
a.reshape(2,2) # 调整为2*2形式的ndarray
(110)转置
对ndarray进行转置。
np.transpose函数和array.T属性返回结果类似。
In [117]:
a = np.array([[1,2],[3,4]]) # 创建ndarray
a.T # 对a进行转置
(111)拼接
拼接多个ndarray。
axis=1表示横向拼接, axis=0表示纵向拼接
In [118]:
a = np.array([[1,2], [3,4]]) # 创建ndarray
np.concatenate((a, a), axis=1) # 拼接
Out[118]:
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
(112)导入pandas模块
下面为导入pandas模块代码惯例。
(113)创建Series1
通过pd.Series函数创建Series。
In [120]:
s = pd.Series([1, 2, 3, 4])
s
Out[120]:
0 1
1 2
2 3
3 4
dtype: int64
(114)创建Series2
通过pd.Series函数创建Series,传入参数为包含映射关系的对象,如字典。
函数运行时将映射关系在前的(如字典键)作为Series的key,在后的作为值。
In [121]:
s = pd.Series({'a':1, 'b':2})
s
(115)创建DataFrame
通过pd.DataFrame函数创建DataFrame,可通过传入colums,index参数设置DataFrame的行index和列名。
In [122]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
df
Out[122]:
|
a |
b |
c |
0 |
1 |
2 |
3 |
1 |
4 |
5 |
6 |
2 |
7 |
8 |
9 |
In [123]:
s = pd.Series([1, 2, 3, 4]) # 创建Series
s.index
Out[123]:
RangeIndex(start=0, stop=4, step=1)
In [124]:
s = pd.Series([1, 2, 3, 4]) # 创建Series
s.values
Out[124]:
array([1, 2, 3, 4], dtype=int64)
(118)修改 Series 索引
通过对index使用等号赋值的方式完成对index的调整。
In [125]:
s = pd.Series([1, 2, 3, 4]) # 创建Series
s.index = ['a', 'b', 'c', 'd'] # 修改索引
s
Out[125]:
a 1
b 2
c 3
d 4
dtype: int64
(119)Series以位置进行索引
通过位置获取Series中某个元素,使用方法类似list的索引。
In [126]:
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c','d']) # 创建Series
s[1]
(120)Series以index进行索引
通过输入Series某一个index的值获得对应的value。
In [127]:
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c','d']) # 创建Series
s['c']
(121)Series以bool值进行索引
通过输入bool值进行索引,如果为True,则获取对应元素,如果为False,则忽略元素。
In [128]:
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c','d']) # 创建Series
s[s > 2] # 以bool值进行索引
(122)Series以位置进行切片
切片方式类似list。
In [129]:
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c','d']) # 创建Series
s[1:3]
(123)Series以index进行切片
series[a:b] 使用a,b两个series中的index进行切片,将获得a,b之间(包含b)的所有数据。
In [130]:
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c','d']) # 创建Series
s['a':'c'] # 以index进行切片,注意包含末尾index对应的value
(124)获得DataFrame行index
使用df.index属性进行获取。
In [131]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
# 创建DataFrame
df.index # 获取index
Out[131]:
RangeIndex(start=0, stop=3, step=1)
(125)获得DataFrame列index(列名)
使用df.columns属性进行获取。
In [132]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
# 创建DataFrame
df.columns # 获取列index
Out[132]:
Index(['a', 'b', 'c'], dtype='object')
(126)修改行index
通过对df.index进行属性赋值方式,完成对行index 的修改。对列属性df.columns修改也可以采用同样方式。
In [133]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
# 创建DataFrame
df.index = ['e', 'f', 'g'] # 修改行index
df
Out[133]:
|
a |
b |
c |
e |
1 |
2 |
3 |
f |
4 |
5 |
6 |
g |
7 |
8 |
9 |
(127)DataFrame获取列数据
通过列index获取DataFrame中某一列数据。
In [134]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
# 创建DataFrame
df['a'] # 进行索引
Out[134]:
0 1
1 4
2 7
Name: a, dtype: int64
(128)DataFrame获取多列数据
通过传入多个列index元素获取DataFrame的相应多列数据。
注意传入参数应为一个包含列index的列表。
In [135]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
# 创建DataFrame
df[['a', 'c']] # 索引多列数据
(129)DataFrame获取行数据1
使用df.loc方法通过传入行index获取行数据。
df.loc[a:b]表示获取从a行开始到b行为止(含b行)数据。
df.loc[a:] 表示获取从a行开始到DataFrame末尾的所有数据。
df.loc[:b] 表示获取从DataFrame首行开始到b行为止(含b行)所有的数据。
df.loc[a:b:s]表示以步长为s获取从a行开始到b行为止之间的所有数据。
In [136]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.loc['x':'z':2] # 以行index进行索引返回行数据
(130)DataFrame获取行数据2
使用df.iloc方法通过传入位置参数获取行数据。
df.iloc[a:b]表示获取从位置a行开始到位置b行为止(不含b行)数据。
df.iloc[a:] 表示获取从位置a行开始到DataFrame末尾的所有数据。
df.iloc[:b] 表示获取从DataFrame首行开始到位置b行为止(不含b行)所有的数据。
df.iloc[a:b:s]表示以步长为s获取从位置a行开始到位置b行为止之间的所有数据。
In [137]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.iloc[0] # 以行位置进行索引返回行数据
Out[137]:
a 1
b 2
c 3
Name: x, dtype: int64
(131)DataFrame获取多行数据1
使用df.loc方法,通过传入多行index获取多行数据。
注意传入参数应为一个包含列index的列表。
In [138]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.loc[['x','y']] # 索引获取多行数据
(132)DataFrame获取多行数据2
使用df.iloc方法,通过传入多行的位置获取多行数据。
注意传入参数应为一个包含列位置的列表。
In [139]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.iloc[[0, 1]] # 以行位置进行索引返回多行数据
(133)以行列 index 获取某个位置数据
使用df.loc方法,通过传入行index,列index获取一个数据。
In [140]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.loc['x', 'a'] # 进行索引返回某个位置数据
(134)以行列位置获取某个位置数据
使用df.iloc方法,通过传入行位置,列位置获取一个数据。
In [141]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.iloc[0, 0] # 进行索引返回某个位置数据
(135)以行列 index 获取某个区域数据
使用df.loc方法,通过传入行列index获取某个区域的数据。
df.loc[a:b, x:y],其中传入的行列标签使用规则参照使用行标签进行索引和使用列标签进行索引。
In [142]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.loc['x':'z', 'b':'c'] # 进行索引返回某个区域数据
(136)以行列位置获取某个区域数据
使用df.iloc方法,通过传入行列位置获取某个区域的数据。
df.iloc[a:b, x:y],其中传入的行列位置使用规则参照使用行位置进行索引,列位置使用规则与行位置规则相似。
In [143]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.iloc[:, 0:2] # 进行索引返回某个区域数据
(137)DataFrame获得前 n 行数据
使用df.head方法获得前n行数据,如果不传入参数,默认获取前5行。
In [144]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.head(2) # 获取前两行数据
(138)DataFrame获得末尾 n行数据
使用df.tail方法获得后n行数据,如果不传入参数,默认获取后5行。
In [145]:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.tail(2) # 获取后两行数据
4.2.3 Series数据清洗、排序、平移、拼接
(139)Series检测缺失值
使用series.isnull方法检测每一个元素是否为nan。
(如果是None,在转化为Series会被转化为np.nan)
In [146]:
s = pd.Series([1, 2, np.nan, 4]) # 创建Series
s.isnull() # 检测nan值
Out[146]:
0 False
1 False
2 True
3 False
dtype: bool
(140)Series填充缺失值
使用series.fillna方法填充缺失值。
常用参数:
value:设置填充时使用值
method:设置填充方式
inplace: 设置是否对当前series进行原地修改
In [147]:
s = pd.Series([1, 2, np.nan, 4]) # 创建Series
s.fillna(method='ffill') # 进行填充
Out[147]:
0 1.0
1 2.0
2 2.0
3 4.0
dtype: float64
(141)Series删除缺失值
使用series.dropna方法删除缺失数据。
常用参数:
inplace: 设置是否对当前series进行原地修改
In [148]:
s = pd.Series([1, 2, np.nan, 4]) # 创建Series
s.dropna() # 进行删除
Out[148]:
0 1.0
1 2.0
3 4.0
dtype: float64
(142)Series以 index 排序
使用series.sort_index方法,根据index的顺序对series进行排序。
常用参数:
ascending: 设置是否升序排序
inplace: 设置是否对当前series进行原地修改
In [149]:
s = pd.Series([1, 2, np.nan, 4], index=[2,3,1,4]) # 创建Series
s.sort_index() # 进行排序
Out[149]:
1 NaN
2 1.0
3 2.0
4 4.0
dtype: float64
(143)Series以值进行排序
使用series.sort_values方法,根据数据值的大小进行排序。
常用参数:
ascending: 设置是否升序排序
inplace: 设置是否对当前series进行原地修改
In [150]:
s = pd.Series([1, 2, np.nan, 4]) # 创建Series
s.sort_values() # 进行排序
Out[150]:
0 1.0
1 2.0
3 4.0
2 NaN
dtype: float64
(144)Series值平移
使用series.shift方法,保持index不动,将数值整体进行平移。进行平移后在首尾出现空值的位置适应np.nan进行填充。
In [151]:
s = pd.Series([1, 2, np.nan, 4]) # 创建Series
s.shift(1)
Out[151]:
0 NaN
1 1.0
2 2.0
3 NaN
dtype: float64
(145)Series拼接
使用series.append另一个Series与原Series进行拼接。
常用参数:
ignore_index;表示进行拼接时是否忽略传入series自身的index。
In [152]:
s1 = pd.Series([1, 2, 3]) # 创建Series s1
s1
In [153]:
s2 = pd.Series([1, 2, 3], index=['a', 'b','c']) # 创建Series s1
s2
Out[154]:
0 1
1 2
2 3
a 1
b 2
c 3
dtype: int64
4.2.4 DataFrame数据清洗、排序、平移、拼接
(146)DataFrame检测缺失值
使用dataframe.isnull方法检测每一个元素是否为nan。
(如果是None,会被转化为np.nan)
In [155]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.isnull() # 检测是否为nan
Out[155]:
|
a |
b |
c |
x |
False |
True |
False |
y |
False |
False |
False |
z |
False |
False |
False |
(147)DataFrame填充缺失值
使用dataframe.fillna方法填充缺失值。
常用参数:
value:设置填充时使用值
method:设置填充方式
inplace: 设置是否对当前dataframe进行原地修改
In [156]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.fillna(method='bfill') # 进行填充
Out[156]:
|
a |
b |
c |
x |
1 |
5.0 |
3 |
y |
4 |
5.0 |
6 |
z |
7 |
8.0 |
9 |
(148)DataFrame删除缺失值
使用dataframe.dropna方法删除缺失数据。
常用参数:
inplace: 设置是否对当前dataframe进行原地修改
how:设置删除判定条件。'any'表示只要存在一个数据为nan,则将该条数据删除;'all'表示该条数据中所有数据都为nan才会将其删除。
axis:删除缺失值时的判定执行方向。'0'表示将一行数据作为一条数据进行判定,'1'表示将一列数据作为一条数据进行判定。
In [157]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','y','z'])
# 创建DataFrame
df.dropna() # 删除缺失值
Out[157]:
|
a |
b |
c |
y |
4 |
5.0 |
6 |
z |
7 |
8.0 |
9 |
(149)DataFrame以index进行排序
使用dataframe.sort_index方法,根据index的顺序对dataframe进行排序。可以根据行index或列index对行或列进行排序。
常用参数:
ascending: 设置是否升序排序
inplace: 设置是否对当前dataframe进行原地修改
axis: '0'表示对行index进行排序,'1'表示对列index(即column)进行排序
In [158]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','z','y'])
# 创建DataFrame
df.sort_index() # 进行排序
Out[158]:
|
a |
b |
c |
x |
1 |
NaN |
3 |
y |
7 |
8.0 |
9 |
z |
4 |
5.0 |
6 |
(150)DataFrame以某值进行排序
使用dataframe.sort_values方法,根据某行或列数值的顺序对dataframe进行排序。可以根据某行值或某列值进行排序。
by:排序时作为标准的行或列index,可以传入单个或包含多个的列表
ascending: 设置是否升序排序
inplace: 设置是否对当前dataframe进行原地修改
axis: '0'表示根据一列数据对多行进行排序,'1'表示根据一行数据对一列进行排序,默认为0
In [159]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','z','y'])
# 创建DataFrame
df.sort_values(by='b', ascending=False) # 进行排序
Out[159]:
|
a |
b |
c |
y |
7 |
8.0 |
9 |
z |
4 |
5.0 |
6 |
x |
1 |
NaN |
3 |
(151)Dataframe与Series合并简单方式。
通过对DataFrame新列使用等号赋值一个Series的方式完成DataFrame与Series合并。合并时将按照dataframe的index,对新列数据使用Series数据进行填充。如果dataframe中某一个index在Series中没有对应值,那么用nan进行填充。
In [160]:
df = pd.DataFrame([[1, np.nan, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'],index=['x','z','y'])
# 创建DataFrame
s = pd.Series([10, 10], index=['x', 'y']) # 创建Series
df['new_column'] = s # 进行合并
df
Out[160]:
|
a |
b |
c |
new_column |
x |
1 |
NaN |
3 |
10.0 |
z |
4 |
5.0 |
6 |
NaN |
y |
7 |
8.0 |
9 |
10.0 |
(152)两个DataFrame进行合并1
使用pd.merge函数或dataframe.merge方法对两个DataFrame进行合并。
(详细使用介绍请参考AQF课程资料)
In [161]:
df1 = pd.DataFrame([['a', np.nan], ['b', 5], ['c', 8]], columns=['key1', 'value1'],index=['x','z','y'])
# 创建DataFrame df1
df1
Out[161]:
|
key1 |
value1 |
x |
a |
NaN |
z |
b |
5.0 |
y |
c |
8.0 |
In [162]:
df2 = pd.DataFrame([['a', 100], ['b', 10], ['c', 100]], columns=['key2', 'value2'],index=['x','z','y'])
# 创建DataFrame df2
df2
Out[162]:
|
key2 |
value2 |
x |
a |
100 |
z |
b |
10 |
y |
c |
100 |
In [163]:
df1.merge(df2, left_on='key1', right_on='key2') # 进行合并
Out[163]:
|
key1 |
value1 |
key2 |
value2 |
0 |
a |
NaN |
a |
100 |
1 |
b |
5.0 |
b |
10 |
2 |
c |
8.0 |
c |
100 |
(153)两个DataFrame进行合并2
参照两个DataFrame的index使用dataframe.join方法对两个DataFrame进行合并。 (详细使用介绍请参考AQF课程资料)
In [164]:
df1 = pd.DataFrame([['a', np.nan], ['b', 5], ['c', 8]], columns=['key1', 'value1'],index=['x','z','y'])
# 创建DataFrame df1
df1
Out[164]:
|
key1 |
value1 |
x |
a |
NaN |
z |
b |
5.0 |
y |
c |
8.0 |
In [165]:
df2 = pd.DataFrame([['a', 100], ['b', 10], ['c', 100]], columns=['key2', 'value2'],index=['x','z','y'])
# 创建DataFrame df2
df2
Out[165]:
|
key2 |
value2 |
x |
a |
100 |
z |
b |
10 |
y |
c |
100 |
Out[166]:
|
key1 |
value1 |
key2 |
value2 |
x |
a |
NaN |
a |
100 |
z |
b |
5.0 |
b |
10 |
y |
c |
8.0 |
c |
100 |
(154)两个DataFrame进行拼接
将多个DataFrame进行拼接 (详细使用介绍请参考AQF课程资料)
In [167]:
df1 = pd.DataFrame([['a', np.nan], ['b', 5], ['c', 8]], columns=['key1', 'value1'],index=['x','z','y'])
# 创建DataFrame df1
df1
Out[167]:
|
key1 |
value1 |
x |
a |
NaN |
z |
b |
5.0 |
y |
c |
8.0 |
In [168]:
df2 = pd.DataFrame([['a', 100], ['b', 10], ['c', 100]], columns=['key2', 'value2'],index=['x','z','y'])
# 创建DataFrame df2
df2
Out[168]:
|
key2 |
value2 |
x |
a |
100 |
z |
b |
10 |
y |
c |
100 |
In [169]:
pd.concat([df1, df2], axis=1) # 进行拼接
Out[169]:
|
key1 |
value1 |
key2 |
value2 |
x |
a |
NaN |
a |
100 |
z |
b |
5.0 |
b |
10 |
y |
c |
8.0 |
c |
100 |
(155)Series汇总统计
利用series.describe方法可以获取当前Series的数据数量,均值,标准差,最大值,最小值,分位数的数据。
In [170]:
s = pd.Series([1, 2, 3, 4, 5]) # 创建Series
s.describe() # 汇总统计
Out[170]:
count 5.000000
mean 3.000000
std 1.581139
min 1.000000
25% 2.000000
50% 3.000000
75% 4.000000
max 5.000000
dtype: float64
(156)Series统计非NaN值数量
利用series.count方法获得Series中非nan值的数据数量。
In [171]:
s = pd.Series([1, 2, 3, 4, 5]) # 创建Series
s.count() # 进行数量统计
(157)Series统计最大值
利用series.max方法获得Series中最大值。
In [172]:
s = pd.Series([1, 2, 3, 4, 5]) # 创建Series
s.max() # 获取最大值
(158)Series统计最小值
利用series.min方法获得Series中最小值。
In [173]:
s = pd.Series([1, 2, 3, 4, 5]) # 创建Series
s.min() # 获取最小值
(159)Series获得最大值索引
利用series.argmax方法获得最大值的index。
In [174]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.argmax() # 获取最大值index
(160)Series获得最小值索引
利用series.argmin方法获得最小值的index。
In [175]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.argmin() # 获取最小值index
(161)Series获得分位数
利用series.quantile方法获得分位数。
In [176]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.quantile(0.25) # 求分位数
(162)Series获得总和
利用series.sum方法获得总和。
In [177]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.sum() # 求和
(163)Series获得平均值
利用series.mean方法获得平均值。
In [178]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.mean() # 求平均值
(164)Series获得算数中位数
利用series.median方法获得中位数。
In [179]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.median() # 求中位数
(165)Series获得平均绝对离差
利用series.mad方法获得平均绝对离差。
In [180]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.mad() # 求平均绝对离差
(166)Series获得方差
利用series.var方法获得方差。
In [181]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.var() # 求方差
(167)Series获得标准差
利用series.std方法获得标准差。
In [182]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.std() # 求标准差
(168)Series获得偏度
利用series.skew方法获得偏度。
In [183]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.skew() # 求偏度
(169)Series获得峰度
利用series.kurt方法获得峰度。
In [184]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.kurt() # 求峰度
(170)Series获得累计和
利用series.cumsum方法获得累计和。
In [185]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.cumsum() # 计算累计和
Out[185]:
a 1
b 3
c 6
d 10
e 15
dtype: int64
(171)Series获得累计最大值
利用series.cummax方法获得累计最大值。
In [186]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.cummax() # 计算累计最大值
Out[186]:
a 1
b 2
c 3
d 4
e 5
dtype: int64
(172)Series获取累计最小值
利用series.cummin方法获得累计最小值。
In [187]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.cummin()
Out[187]:
a 1
b 1
c 1
d 1
e 1
dtype: int64
(173)Series获取累计乘积
利用series.cumprod方法获得累计乘积。
In [188]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.cumprod() # 求累计乘积
Out[188]:
a 1
b 2
c 6
d 24
e 120
dtype: int64
(174)Series计算一阶差分
利用series.diff函数计算一阶差分。
In [189]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.diff() # 计算一阶差分
Out[189]:
a NaN
b 1.0
c 1.0
d 1.0
e 1.0
dtype: float64
(175)Series计算百分数变化
利用series.pct_change方法计算百分比变化。
In [190]:
s = pd.Series([1, 2, 3, 4, 5],
index=['a','b','c','d','e']) # 创建Series
s.pct_change() # 计算百分比变化
Out[190]:
a NaN
b 1.000000
c 0.500000
d 0.333333
e 0.250000
dtype: float64
(176)计算两个series协方差
利用series.cov方法计算两个series的协方差。
In [191]:
s1 = pd.Series([1,2,3,4]) # 创建series s1
s2 = pd.Series([1,2,4,2]) # 创建series s2
(177)计算两个Series相关系数
利用series.corr方法计算两个series的相关系数。
In [193]:
s1 = pd.Series([1,2,3,4]) # 创建series s1
s2 = pd.Series([1,2,4,2]) # 创建series s2
(178)Series移动窗口函数使用1
利用series.rolling方法获得一个移动窗口进行运算。
该方法常用于时间序列处理。
In [195]:
s = pd.Series([1,2,3,4,2,4,5,3,5,2]) # 创建series
In [196]:
s.rolling(3).mean() # 利用移动窗口计算平均值
Out[196]:
0 NaN
1 NaN
2 2.000000
3 3.000000
4 3.000000
5 3.333333
6 3.666667
7 4.000000
8 4.333333
9 3.333333
dtype: float64
(179)Series移动窗口函数使用2
利用series.rolling方法获得一个移动窗口进行运算。
该方法常用于时间序列处理。
In [197]:
s.rolling(3).apply(np.mean)
Out[197]:
0 NaN
1 NaN
2 2.000000
3 3.000000
4 3.000000
5 3.333333
6 3.666667
7 4.000000
8 4.333333
9 3.333333
dtype: float64
(180)DataFrame汇总统计
利用df.describe方法获得各列的数据数量,平均值,标准差,最小值,分位数,最大值。
In [198]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.describe() # 获得汇总统计
Out[198]:
|
a |
b |
count |
4.000000 |
4.000000 |
mean |
5.500000 |
6.500000 |
std |
3.872983 |
3.872983 |
min |
1.000000 |
2.000000 |
25% |
3.250000 |
4.250000 |
50% |
5.500000 |
6.500000 |
75% |
7.750000 |
8.750000 |
max |
10.000000 |
11.000000 |
(181)DataFrame统计非NaN值数量
利用df.count方法获得各列(或行)非nan值的数据数量。
In [199]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.count() # 计数
(182)DataFrame统计最大值
利用df.max方法获得各列(或行)最大值。
In [200]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.max() # 求最大值
(183)DataFrame统计最小值
利用df.min方法获得各列(或行)最小值。
In [201]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.min() # 求最小值
(184)DataFrame获得分位数
利用df.quantile方法获得各列(或行)分位数。
In [202]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.quantile(0.25) # 求分位数
Out[202]:
a 3.25
b 4.25
Name: 0.25, dtype: float64
(185)DataFrame获得总和
利用df.sum方法获得各列(或行)总和。
In [203]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.sum() # 求总和
(186)DataFrame获得平均值
利用df.mean方法获得各列(或行)平均值。
In [204]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.mean() # 求平均值
Out[204]:
a 5.5
b 6.5
dtype: float64
(187)DataFrame获得算数中位数
利用df.median方法获得各列(或行)中位数
In [205]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.median() # 求中位数
Out[205]:
a 5.5
b 6.5
dtype: float64
(188)DataFrame获得平均绝对离差
利用df.mad方法获得各列(或行)平均绝对离差。
In [206]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.mad() # 求平均绝对离差
Out[206]:
a 3.0
b 3.0
dtype: float64
(189)DataFrame获得方差
利用df.var方法获得各列(或行)方差。
In [207]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.var() # 求方差
Out[207]:
a 15.0
b 15.0
dtype: float64
(190)DataFrame获得标准差
利用df.std方法获得各列(或行)标准差。
In [208]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.std() # 求标准差
Out[208]:
a 3.872983
b 3.872983
dtype: float64
(191)DataFrame获得偏度
利用df.skew方法获得各列(或行)偏度。
In [209]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.skew() # 求偏度
Out[209]:
a 0.0
b 0.0
dtype: float64
(192)DataFrame获得峰度
利用df.kurt方法获得各列(或行)峰度。
In [210]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.kurt() # 求峰度
Out[210]:
a -1.2
b -1.2
dtype: float64
(193)DataFrame获得累计和
利用df.cumsum方法获得各列(或行)累计和。
In [211]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.cumsum() # 求累计和
Out[211]:
|
a |
b |
0 |
1 |
2 |
1 |
5 |
7 |
2 |
12 |
15 |
3 |
22 |
26 |
(194)DataFrame获得累计最大值
利用df.cummax方法获得各列(或行)累计最大值。
In [212]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.cummax() # 求累计最大值
Out[212]:
|
a |
b |
0 |
1 |
2 |
1 |
4 |
5 |
2 |
7 |
8 |
3 |
10 |
11 |
(195)DataFrame获取累计最小值
利用df.cummin方法获得各列(或行)累计最小值。
In [213]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.cummin() # 求累计最小值
Out[213]:
|
a |
b |
0 |
1 |
2 |
1 |
1 |
2 |
2 |
1 |
2 |
3 |
1 |
2 |
(196)DataFrame获取累计乘积
利用df.cumprod方法获得各列(或行)的累计乘积。
In [214]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.cumprod() # 求累计乘积
Out[214]:
|
a |
b |
0 |
1 |
2 |
1 |
4 |
10 |
2 |
28 |
80 |
3 |
280 |
880 |
(197)DataFrame计算百分数变化
利用df.pct_change方法获得各列数据的百分比变化。
常用参数:
periods:用于确定计算百分比变化选定的窗口期数,默认为1
In [215]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.pct_change(periods=2) # 求百分比变化
Out[215]:
|
a |
b |
0 |
NaN |
NaN |
1 |
NaN |
NaN |
2 |
6.0 |
3.0 |
3 |
1.5 |
1.2 |
(198)DataFrame计算各列协方差矩阵
利用df.cov方法获得各列数据的协方差矩阵。
In [216]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.cov() # 求协方差矩阵
Out[216]:
|
a |
b |
a |
15.0 |
15.0 |
b |
15.0 |
15.0 |
(199)DataFrame计算各列相关系数矩阵
利用df.corr方法获得各列数据的相关系数矩阵。
In [217]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.corr() # 求相关系数矩阵
(200)DataFrame各列分别计算与一个Series之间的相关系数
利用df.corrwith方法获得dataframe各列与series数据之间的相关系数。
In [218]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
s = pd.Series([2,3,6]) # 创建Series
df.corrwith(s) # 求相关系数
Out[218]:
a 0.960769
b 0.960769
dtype: float64
(201)DataFrame移动窗口函数1
利用df.rolling方法获得一个移动窗口进行运算。
该方法常用于时间序列处理。
In [219]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.rolling(3).mean() # 计算移动平均
Out[219]:
|
a |
b |
0 |
NaN |
NaN |
1 |
NaN |
NaN |
2 |
4.0 |
5.0 |
3 |
7.0 |
8.0 |
(202)DataFrame移动窗口函数1
利用df.rolling方法获得一个移动窗口进行运算。
该方法常用于时间序列处理。
In [220]:
df = pd.DataFrame([[1, 2], [4, 5], [7, 8], [10, 11]], columns=['a', 'b'])
# 创建dataframe
df.rolling(3).apply(np.mean) # 计算移动平均
Out[220]:
|
a |
b |
0 |
NaN |
NaN |
1 |
NaN |
NaN |
2 |
4.0 |
5.0 |
3 |
7.0 |
8.0 |
(203)DataFrame的Groupby技术1
利用df.groupby方法根据某列(或行)对数据进行聚合后进行运算。
常用参数:
by:常输入字符串或元素为字符串的列表,选择列index与之相同的列作为聚合依据。
In [221]:
df = pd.DataFrame([['a',2], ['a',35], ['b',2], ['a',6], ['c',5]],
columns=['name', 'number'])
# 创建dataframe
df
Out[221]:
|
name |
number |
0 |
a |
2 |
1 |
a |
35 |
2 |
b |
2 |
3 |
a |
6 |
4 |
c |
5 |
In [222]:
df.groupby('name').mean() # 分组计算平均值
Out[222]:
|
number |
name |
|
a |
14.333333 |
b |
2.000000 |
c |
5.000000 |
(204)DataFrame的Groupby技术1
利用df.groupby方法根据某列(或行)对数据进行聚合后进行运算。
常用参数:
by:常输入字符串或元素为字符串的列表,选择列index与之相同的列作为聚合依据。
In [223]:
df = pd.DataFrame([['a',2], ['a',35], ['b',2], ['a',6], ['c',5]],
columns=['name', 'number'])
# 创建dataframe
df
Out[223]:
|
name |
number |
0 |
a |
2 |
1 |
a |
35 |
2 |
b |
2 |
3 |
a |
6 |
4 |
c |
5 |
In [224]:
df.groupby('name').apply(np.mean) # 分组计算平均值
Out[224]:
|
number |
name |
|
a |
14.333333 |
b |
2.000000 |
c |
5.000000 |
(205)日期字符串转化为datetime
利用pd.to_datetime函数将日期字符串转化为Datetimeindex用于作为某DataFrame的index。
通过该函数获得的DatetimeIndex为后续时间序列处理做准备。
In [225]:
pd.to_datetime(['2017-8-1', '2017-8-2'])
Out[225]:
DatetimeIndex(['2017-08-01', '2017-08-02'], dtype='datetime64[ns]', freq=None)
(206)生成指定DatetimeIndex
使用pd.date_range函数通过指定时间长度和频率生成DatetimeIndex。
常用参数:
start:起始时间
end:结束时间
periods:时间周期数量
freq:时间频率
In [226]:
pd.date_range('2017-8-1', periods=5, freq='d')
Out[226]:
DatetimeIndex(['2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04',
'2017-08-05'],
dtype='datetime64[ns]', freq='D')
(207)生成指定PeriodIndex
使用pd.period_range函数生成固定频率的PeriodIndex。
常用参数:
(参照pd.date_range函数)
In [227]:
pd.period_range('2017-8-1', periods=5, freq='d')
Out[227]:
PeriodIndex(['2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04',
'2017-08-05'],
dtype='period[D]', freq='D')
(208)时间序列索引
可参考DataFrame索引的方式。特别的,时间序列可对较高级时间进行索引,如对日频率时间序列进行月索引。
In [228]:
s = pd.Series([1, 2, 3, 4, 5]) # 创建被索引对象
s.index = pd.date_range('2017-7-29', periods=5)
s
Out[228]:
2017-07-29 1
2017-07-30 2
2017-07-31 3
2017-08-01 4
2017-08-02 5
Freq: D, dtype: int64
In [229]:
s.loc['2017-7'] # 索引月级别数据
Out[229]:
2017-07-29 1
2017-07-30 2
2017-07-31 3
Freq: D, dtype: int64
(209)转换时间序列频率
利用df.resample方法将时间序列转化为指定时间频率的时间序列,通常在之后使用.function完成相关运算,如聚合。
常用参数:
rule:指定时间频率
In [230]:
s = pd.Series(np.random.randn(10)) # 创建被索引对象
s.index = pd.date_range('2017-7-25', periods=10)
s
Out[230]:
2017-07-25 2.365549
2017-07-26 -1.049833
2017-07-27 -0.469093
2017-07-28 0.940941
2017-07-29 -1.623167
2017-07-30 0.934857
2017-07-31 0.290800
2017-08-01 -0.202417
2017-08-02 0.171327
2017-08-03 -0.317472
Freq: D, dtype: float64
In [231]:
s.resample('M').ohlc()
# 等价于s.resample('M', how='ohlc')
Out[231]:
|
open |
high |
low |
close |
2017-07-31 |
2.365549 |
2.365549 |
-1.623167 |
0.290800 |
2017-08-31 |
-0.202417 |
0.171327 |
-0.317472 |
-0.317472 |
(210)csv文件读取
使用pd.read_csv函数读取csv文件,返回DataFrame或Series。
常用参数:
sep:设置读取数据时,分隔一行数据中各个元素的符号,默认为','
header:设置作为列名的行数
names:如果header=None,则通过names进行列名设置
index_col:设置作为index的列
skiprows:跳过某一行不获取数据
(211)excel文件读取
使用pd.excel函数读取excel文件,返回DataFrame或Series。
常用参数:
sheetname:可以通过输入字符串或整数确定将要读取的sheet
(其他参数可按照pd.read_csv函数)
(212)储存为csv文件
利用df.to_csv方法将当前DataFrame保存为指定文件。
In [232]:
df = pd.DataFrame([['a',2], ['a',35], ['b',2], ['a',6], ['c',5]],
columns=['name', 'number'])
# 创建dataframe
df.to_csv('test.txt')
(213)储存为excel文件
利用df.to_excel方法将当前DataFrame保存为指定文件
In [233]:
df = pd.DataFrame([['a',2], ['a',35], ['b',2], ['a',6], ['c',5]],
columns=['name', 'number'])
# 创建dataframe
df.to_excel('test.xls')