2.Pandas
使用Pandas处理数据
导入包:
import pandas as pd import numpy as np
2.1Pandas对象
包括Series对象,DataFrame对象,Index对象
实例1:
Series对象结构:一组数据和一组索引,数据类型;
def pandas1():
'''
Pandas数据对象
:return:
'''
#使用列表创建Series对象
se1 = pd.Series([0.23,3,0.24,11])
print(se1)
#获取数据,索引
print(se1.values)
print(se1.index)
#创建方式2:Series对象
se2 = pd.Series([1,2,5,20],index=['a','b','c','d'])
print(se2)
#Series类似python字典
dict1 = dict({"1":"hello","2":"world","3":"python"})
se3 = pd.Series(dict1)
print(se3)
#使用标量填充index
se4 = pd.Series(5,index=["a","b","c"])
print(se4)
实例2:
DataFrame对象,和Series类似,Series相当于一维数组,DataFrame相当于二维数组。
实例:
def pandas2():
'''
Pandas数据对象:DataFrame
:return:
'''
se1 = pd.Series({'1':"tom","2":"jame","3":"jay"})
se2 = pd.Series({"1":"sx","2":"cq","3":"cd"})
df1 = pd.DataFrame({'name':se1,"addr":se2})
print(df1)
#行索引
print(df1.index)
#列索引
print(df1.columns)
#创建单列dataFrame
df2 = pd.DataFrame(se1,columns=["name"])
print(df2)
#通过列表创建
list1 = [{"a":i,"b":i*2,"c":i+1} for i in range(5)]
df3 = pd.DataFrame(list1)
print(df3)
#通过numpy多维数组创建
np1 = np.random.rand(3,2)
df4 = pd.DataFrame(np1,columns=["col1","col2"],index=["1","2","3"])
print(df4)
实例3:
Pandas的Index对象,一个不可变的数组或有序集合
def pandas3():
'''
pandas数据对象:Index
:return:
'''
#创建
ind1 = pd.Index([1,2,3,4])
print(ind1)
#可以包含重复值
ind2 = pd.Index([1,2,3,4,4,6,9])
print(ind2)
#属性
print(ind1.size)
print(ind1.shape)
print(ind1.ndim)
print(ind1.dtype)
#可以执行集合运算
ind3 = ind1 & ind2
print(ind3)
ind4 = ind1 | ind2
print(ind4)
#异或
ind5 = ind1 ^ ind2
#前面方式已经弃用
#并集
ind6 = pd.Index.union(ind1,ind2)
print(ind6)
#交集
ind7 = pd.Index.intersection(ind1,ind2)
print(ind7)
#差集
ind8 = pd.Index.difference(ind1,ind2)
print(ind8)
#异或
ind9 = pd.Index.symmetric_difference(ind1,ind2)
print(ind9)
2.2Pandas数据取值与选择
包括Series对象数据选择,DataFrame对象数据选择
实例1:Series数据选择
def pandas4():
'''
Series对象数据选择
:return:
'''
se1 = pd.Series([1,2,5,10,99],index=['a','b','c','d','e'])
#类似字典键值获取
print(se1['a'])
#获取所有键
print(se1.index)
#获取所有键值对
print(list(se1.items()))
#通过索引切片
se2 = se1['a':'c']
print(se2)
#通过隐式索引,默认从0依次编号
se3 = se1[0:2]
print(se3)
#掩码筛选
se4 = se1[(se1 > 3) & (se1 <=6 )]
print(se4)
#索引列表
se5 = se1[['a','c']]
print(se5)
#注意:显示索引和隐式索引使用的时机
se6 = pd.Series([1,3,5,6,10,22],index=[1,2,3,4,5,6])
#这里使用的显示索引
se7 = se6[1]
print(se7)
#这里使用隐式索引
se8 = se6[1:3]
print(se8)
#避免索引混淆
#通过loc,使用显示索引
se9 = se6.loc[1]
se10 = se6.loc[1:3]
print(se9)
print(se10)
#通过iloc,使用隐式索引
se11 = se6.iloc[1]
se12 = se6.iloc[1:3]
print(se11)
print(se12)
实例2:DataFrame数据选择
def pandas5():
'''
pandas:Dataframe数据选择
:return:
'''
se1 = pd.Series({'1':"tom","2":"jame","3":"jay"})
se2 = pd.Series({"1":"sx","2":"cq","3":"cd"})
df1 = pd.DataFrame({'name':se1,"addr":se2})
print(df1)
#通过列名获取某列
print(df1['name'])
#通过属性方式
print(df1.name)
#增加一列
df1['count'] = {'1':11,"2":32,"3":40}
print(df1)
#查看数据
print(df1.values)
#行列转置
print(df1.T)
#获取某行数据
print(df1.values[1])
#获取某列数据
print(df1["name"])
#切片
#隐式
print(df1.iloc[:1,:1])
#第一行
print(df1[1:2])
#显式
print(df1.loc[:'3',:'addr'])
#索引列表
print(df1[['name','addr']])
2.3Pandas数据运算
包括Pandas算术运算,三角函数,指数,对数运算。
实例1:
def pandas6():
'''
Pandas运算
:return:
'''
data1 = np.random.randint(10,size=(4,3))
print(data1)
df1 = pd.DataFrame(data1,columns=['A','B','C'])
#Pandas的通用函数和Numpy的一致
#指数运算
#e的多少次方
df2 = np.exp(df1)
print(df2)
#2的多少次方
df3 = np.exp2(df1)
print(df3)
#3的多少次方
df4 = np.power(3,df1)
print(df4)
#对数运算
df5 = np.log(df1)
print(df5)
#Pandas索引对齐
se1 = pd.Series({'tom':100,"jay":1039,"min":103})
se2 = pd.Series({'tom':10,"jane":22,"sali":11,"min":5})
#生成一个dataFrame,index对齐
se21 = se1 / se2
print(se21)
#获取series 索引并集
se21_ind = se1.index | se2.index
print(se21_ind)
#加法
se3 = pd.Series([3,4,5],index=[0,1,2])
se4 = pd.Series([3,4,6],index=[1,2,4])
#会出现当对应index某一个Series没值,返回NaN
se34 = se3 + se4
print(se34)
#当没值时,对应Series位置值为0
se34 = se3.add(se4,fill_value=0)
print(se34)
#Dataframe运算
df11 = pd.DataFrame(np.random.randint(10,size=(3,3)),columns=['A','B','C'])
df12 = pd.DataFrame(np.random.randint(10,size=(2,2)),columns=['A','B'])
#加法
#同样对应位置相加,一个参数对应位置没值,返回Nan
df13 = df11 + df12
print(df11)
print(df12)
print(df13)
#减法
df14 = df11 - df12
print(df14)
#+ add
#- sub, subtract
#* mul, multiply
#/ truediv,div,divide
#// floordiv
#% mode
#** pow
df15 = df11.sub(df12,fill_value=0)
print(df15)
#减去某行,隐式索引
df16 = df11.sub(df11.iloc[0])
print(df16)
#减去某列
df17 = df11.subtract(df11['A'],axis=0)
print(df17)
2.4Pandas处理缺失值
Python的缺失值表示:None,是一个Python对象,当使用None时,列表的类型为Object
Python的缺失值表示:NaN,可以用于sum(),min()等计算,都返回NaN
实例:
def pandas7():
'''
pandas处理缺失值
:return:
'''
#发现缺失值
#isnull()
#notnull()
se1 = pd.Series([1,np.nan,None,2,3,5])
#返回缺失值判断Series
print(se1.isnull())
print(se1.notnull())
#删除缺失值
#dropna(),删除nan值
se2 = se1.dropna()
print(se2)
#dataFrame,删除nan值
df1 = pd.DataFrame([[
1,np.nan,2],
[2,3,np.nan],
[np.nan,4,5]
])
#会删除任意有NaN的行
df2 = df1.dropna()
print(df2)
#删除任意有Nan的列
df3 = df1.dropna(axis='columns')
print(df3)
#删除所有值都是NaN的行
df4 = df1.dropna(how='all')
print(df4)
#设置行缺失值的最大阈值,最多缺失1个值
df5 = df1.dropna(thresh=1)
print(df5)
#fillna(),缺失值填充
#使用0填充
df6 = df1.fillna(0)
print(df6)
#缺失值前的值填充
df7 = df1.fillna(method='ffill')
print(df7)
#缺失值后的值填充
df8 = df1.fillna(method='bfill')
print(df8)
#使用坐标轴,列方向填充
df9 = df1.fillna(method='ffill',axis=1)
print(df9)
2.5Pandas层级索引
Pandas提供Panel,Panel4D处理三维,四维数据。多级索引方式处理多维数据。
实例:
def pandas8():
'''
pandas层级索引
:return:
'''
#旧有多层索引实现
index1 = [('重庆',2000),('陕西',2000),('四川',2008),('北京',2008)]
data1 = [2000,1800,3000,5000]
se1 = pd.Series(data1,index=index1)
#创建层级索引
mul_ind1 = pd.MultiIndex.from_tuples(index1)
print(mul_ind1)
#将普通索引转换为层级索引
se2 = se1.reindex(mul_ind1)
print(se1)
print(se2)
#层级索引切片操作
se3 = se2[:,2000]
print(se3)
#将多层级索引Series转换为DataFrame
df1 = se2.unstack()
print(df1)
#反向转换
se4 = df1.stack()
print(se4)
#多级索引创建
df2 = pd.DataFrame(np.random.randint(10,size=(3,2)),
index=[['a','a','b'],[1,2,1]],
columns=["data1","data2"])
print(df2)
#字典的键为元组,默认创建多层索引
data2 = {
("重庆",2000):10023,
("四川",2000):20033,
("陕西",2002):20393,
("北京",2001):10391,
("北京",2000):23922
}
se5 = pd.Series(data2)
print(se5)
#创建索引
#tuple列表
#pd.MultiIndex.from_tuples()
#array列表
mul_ind2 = pd.MultiIndex.from_arrays([['中国','美国','英国'],[2000,2011,2003]],names=['国家','年度'])
#笛卡尔集
mul_ind3 = pd.MultiIndex.from_product([['1月','2月'],['上','下']],names=['月份','半月'])
print(mul_ind3)
#创建多级索引名称
se5.index.names = ['省份','年份']
print(se5)
#多级索引取值
print(se5['北京',2000])
print(se5['北京'])
print(se5[se5 > 20100])
print(se5[:,2000])
print(se5[['北京','重庆']])
#多级行列索引
data3 = np.random.randint(10000,size=(3,4))
print(data3)
df2 = pd.DataFrame(data=data3,index=mul_ind2,columns=mul_ind3)
print(df2)
#iloc隐式索引
print(df2.iloc[1:2,0:2])
#多个层级索引
print(df2.loc[:,('1月','上')])
print(df2.loc[('美国',), ("1月", "下")])
#索引中使用切片元组会报错,使用slice
#print(df2.iloc[(:,1),(:,2)])
indexS = pd.IndexSlice
print(df2.loc[indexS[:'美国'],indexS[:'下']])
#当多级索引顺序是混乱的话,切片操作会失败
#对索引进行排序
df3 = df2.sort_index()
print(df3)
#索引的stack,unstack
print(df2.unstack(level=0))
print(df2.unstack(level=1))
#保持原样
print(df2.unstack().stack())
#多级索引数据累计
df4 = df2.mean(level=1)
print(df4)
#列标签的维度加总
df5 = df2.sum(level=1,axis=1)
print(df5)
2.6Pandas数据集连接
Pandas通过concat,append合并一维的Series,多维的DataFrame
实例:
def pandas9():
'''
pandas concat合并
:return:
'''
se1 = pd.Series(['A','B','C'],index=[1,2,3])
se2 = pd.Series(['D','B','F'],index=[4,5,8])
se3 = pd.concat([se1,se2])
print(se3)
df1 = pd.DataFrame(np.random.randint(10,size=(4,4)),columns=['A','B','C','D'])
df2 = pd.DataFrame(np.random.randint(10, size=(4, 4)), columns=['A', 'B', 'C','D'])
print(df1)
print(df2)
#默认行合并
print(pd.concat([df1,df2],axis=0))
#列合并,axis=1
print(pd.concat([df1,df2],axis=1))
#合并后,可以发现索引是重复的
#如何处理索引重复
#存在索引重复报错
#print(pd.concat([df1,df2],verify_integrity=True))
#忽略原来索引,重新生成索引
print(pd.concat([df1,df2],ignore_index=True))
#根据索引上生成多级索引
print(pd.concat([df1,df2],keys=['df1','df2']))
#join=设置连接方式
#取交集
print(pd.concat([df1,df2],join='inner'))
#默认取并集
#print(pd.concat([df1,df2],join='outer'))
#append方法
print(df1.append(df2))
2.7Pandas数据集合并
Pandas通过join,merge实现内存式数据连接。merge方法功能实现基于关系代数。数据连接类型:一对一,一对多,多对多。
实例:
def pandas10():
'''
pandas
:return:
'''
df1 = pd.DataFrame({
'people':['Bo','Tom','Jane','Lisa'],
'group':['HR','PP','SD','MM']
})
df2 = pd.DataFrame({
'people':['Bo','Jane','Lisa','Tom'],
'year':[2023,2021,2000,2021]
})
print(df1)
print(df2)
#两个数据框连接成一个
#自动使用people列连接,使用新的行索引
df3 = pd.merge(df1,df2)
print(df3)
#多对一
df4 = pd.DataFrame({
'group':['HR','PP','SD','MM'],
'num': [1030, 2000, 1033, 1001]
})
df5 = pd.DataFrame({
'people':['Bo','Tom','Jame'],
'group':['HR','PP','PP']
})
df6 = pd.merge(df4,df5)
print(df6)
#多对多
df7 = pd.DataFrame({
'people':['Bo','Tom','Jame'],
'group':['HR','PP','PP']
})
df8 = pd.DataFrame({
'people':['Bo','Bo','Tom','Jame'],
'work':['excel','word','ppt','excel']
})
df9 = pd.merge(df7,df8)
print(df9)
#通过on设置连接的列,或列表
#只能有相同列名才能使用
print(pd.merge(df7,df8,on='people'))
#当需要连接的列名不同时
df11 = pd.DataFrame({
'name':['Bo','Tom','Jame'],
'group':['HR','PP','PP']
})
df12 = pd.DataFrame({
'people':['Bo','Bo','Tom','Jame'],
'work':['excel','word','ppt','excel']
})
df13 = pd.merge(df11,df12,left_on='name',right_on='people')
print(df13)
#通过drop删除多余列
print(df13.drop('people',axis=1))
#通过索引连接
df14 = pd.DataFrame({
'name': ['Bo', 'Tom', 'Jame','Sary'],
'group': ['HR', 'PP', 'PP','MM']
})
df15 = pd.DataFrame({
'people': ['Bo', 'Bo', 'Tom', 'Jame','Lin'],
'work': ['excel', 'word', 'ppt', 'excel','word']
})
#将name,people列设置为index
df14_i = df14.set_index('name')
df15_i = df15.set_index('people')
print(df14_i)
print(df15_i)
#通过索引连接
#left_index将左边表index设置为列,然后连接
#right_index将右边表index设置为列,然后连接
df16 = pd.merge(df14_i,df15_i,left_index=True,right_index=True)
print(df16)
#join方法,直接使用index连接
df16_join = df14_i.join(df15_i)
print(df16_join)
#结合使用
df17 = pd.merge(df14_i,df15,left_index=True,right_on='people')
print(df17)
#默认merge都是内连接,获取两个数据集交集,默认inner
df18 = pd.merge(df14,df15,left_on='name',right_on='people',how='inner')
print(df18)
#outer:保留两个表记录,没有对应值的使用NaN
df19 = pd.merge(df14,df15,left_on='name',right_on='people',how='outer')
print(df19)
#left:保留左边表所有记录,缺失值Nan,右边表只保留有对应值的记录
df20 = pd.merge(df14,df15,left_on='name',right_on='people',how='left')
print(df20)
#right:保留右边表所有记录,缺失值Nan,左边表只保留有对应值的记录
df21 = pd.merge(df14,df15,left_on='name',right_on='people',how='right')
print(df21)
#重复列名处理
df22 = pd.DataFrame({
'name': ['Bo', 'Tom', 'Jame','Sary'],
'group': ['HR', 'PP', 'PP','MM']
})
df23 = pd.DataFrame({
'name': ['Bo', 'Bo', 'Tom', 'Jame','Lin'],
'group': ['BG', 'SD', 'BG', 'BG','BU']
})
#默认将同名列添加_x,_y,这里group_x,group_y
df24 = pd.merge(df22,df23,on='name')
print(df24)
#设置同名列规则,添加_L,_R
df25 = pd.merge(df22,df23,on='name',suffixes=['_L','_R'])
print(df25)
2.8Pandas数据集累计分组
Pandas计算一些累计数据。sum(),mean(),median(),min(),max()等功能。
实例:
def pandas11():
'''
pandas累计与分组
:return:
'''
#导入数据airplanes.csv
df_data = pd.read_csv('airplanes.csv')
print(df_data)
#Series简单累计
se1 = pd.Series(np.random.randint(100,size=(100)))
print(se1.sum())
print(se1.mean())
print(se1.max())
print(se1.min())
print(se1.median())
#DataFrame累计
#默认对每列axis=0统计
df1 = pd.DataFrame({'A':np.random.randint(100,size=(10)),'B':np.random.randint(100,size=(10))})
print(df1)
print(df1.mean())
print(df1.max())
print(df1.min())
print(df1.sum())
print(df1.median())
#对每行统计
print(df1.max(axis=1))
#print(df1.max(axis='columns'))
#直接使用describe显示信息
print(df1.describe())
#聚合方法列表
#count() 计数
#first() last() 第一项,最后一项
#mean() 均值
#median() 中位数
#min() max() 最小最大值
#std() var() 标准差,方差
#mad() 均值绝对偏差
#prod() 所以项乘积
# sum() 求和
#分组
#groupby方法
df2 = pd.DataFrame({'key':['A','A','B','C','C','D'],'value':[10,11,44,22,55,14]})
print(df2.groupby('key'))
# groupby对象可以看作特色的DataFrame,调用聚合方法
print(df2.groupby('key').sum())
print(df2.groupby('key').max())
#按列取值
#添加随机数列
df_data['data1'] = np.random.rand(len(df_data))
df_data['data2'] = np.random.randint(1000,size=len(df_data))
#设置数据列名
print(df_data)
#获取为SeriesGroupBy对象,使用聚合方法获取数据
#根据TailNum统计number列
df3 = df_data.groupby('TailNum')['data1']
#查看数据
print(df3)
print(df3.median())
#获取describe详细数据
print(df3.describe())
#使用aggregate(),计算多个聚合方法
print(df3.aggregate(['min',np.median,max]))
#过滤
def filter_func(x):
return x['data2'].mean()> 500
print(df_data.groupby('TailNum').mean())
print(df_data.groupby('TailNum').filter(filter_func))
#转换,返回一个同样结构的数据。
#将分组数据减去均值,实现数据标准化
print(df_data.groupby('TailNum').transform(lambda x: x-x.mean()))
#apply,实现不同列数据标准化
#让data1加上data2列数据和
print(df_data.groupby('TailNum').apply(lambda x:x['data1'] + x['data2'].sum()))
#分组groupby
#使用list数据,分为5组,size和DataFrame大小匹配
list1 = np.random.randint(5,size=(len(df_data)))
print(list1)
print(df_data.groupby(list1).sum())
#使用字典定义索引映射关系
df_data1 = pd.DataFrame({'key':['A','B','C','D'],'data1':[1,2,5,6],'data2':[3,5,7,4]},columns=['key','data1','data2'])
#将key设置为索引
df_data1 = df_data1.set_index('key')
#定义映射关系
dict_mapping = {'A':'part1','B':'part2','C':'part2','D':'part1'}
print(df_data1.groupby(dict_mapping).sum())
#使用函数,转换聚合键值
print(df_data1.groupby(str.lower).sum())
#传入list,构建多级索引
print(df_data1.groupby(['key',dict_mapping]).sum())
2.9Pandas数据透视表
Pandas数据透视表类似Excel数据透视表。将每一列数据输入,输出多个维度的二维信息表。
实例:
def pandas12():
'''
pandas数据透视表
:return:
'''
df_data1 = pd.DataFrame({
'name':['tom','jay','fele','jack','bill'],
'group':['gp1','gp2','gp1','gp2','gp1'],
'step':['step1','step2','step1','step3','step2'],
'score':[93,49,63,100,89]
},columns=['name','group','step','score'])
print(df_data1)
print(df_data1.groupby('group')[['score']].mean())
#多维度分组
print(df_data1.groupby(['group','step'])['score'].mean())
#使用pivot_table,查看多维度分组数据
print(df_data1.pivot_table('score',index='group',columns='step'))
#如果将数字分组,自定义阶段范围
p_score = pd.cut(df_data1['score'],[60,80,100])
print(df_data1.pivot_table('score',index=['step',p_score],columns='group'))
#同样方式qcut,根据数据情况分成两组
p_score = pd.qcut(df_data1['score'],2)
print(df_data1.pivot_table('score',index=['step',p_score],columns='group'))
#处理空值
print(df_data1.pivot_table('score',index='step',columns='group',fill_value=0))
print(df_data1.pivot_table('score',index='step',columns='group',dropna=True))
#aggfunc
#mean , sum , max , min , count,
print(df_data1.pivot_table('score',index='group',columns='step',aggfunc='mean'))
#可以为不同列指定不同汇总方法
print(df_data1.pivot_table('score',index='group',columns='step',aggfunc={'score':'sum','score':'count'}))
#计算每组的统计值
print(df_data1.pivot_table('score',index='group',columns='step',aggfunc='mean',margins=True,margins_name='All_mean'))
2.10Pandas向量化字符串
使用Pandas处理字符串列表
实例:
def pandas13():
'''
pandas向量化字符串
:return:
'''
names = pd.Series(['peter','Tom','Mary','HOM'])
#使用str,处理字符串列表
#首字母大写
print(names.str.capitalize())
#字符串列表,字符长度
print(names.str.len())
#字符串列表,字符串小写
print(names.str.lower())
#字符串列表,字符串大写
print(names.str.upper())
#ljust() rjust()
print(names.str.ljust(10,'*'))
print(names.str.rjust(10,'*'))
#center()
print(names.str.center(10,'*'))
#find() rfind()
#没找到-1,找到返回所在索引
print(names.str.find('M'))
#zfill(),用0填充字符串
print(names.str.zfill(10))
#index() rindex(),查找对应字符串位置
#print(names.str.index('M'))
#strip() rstrip() lstrip()
#移除两端指定字符
print(names.str.strip('M'))
#swapcase() 大小写互转
print(names.str.swapcase())
#translate()
trans_str = str.maketrans('abcdefg','1234567')
#参数1:转换对应关系表,参数2:要删除字符表
print(names.str.translate(trans_str))
#split() 拆分 rsplit 右边拆分
print(pd.Series(['hello,tom','world,hi','test,txt']).str.split(','))
#partition() 给定字符串部分切分, rpartition()
print(names.str.partition('M'))
#startswith() endswith() 以什么开头,结尾
print(names.str.startswith('M'))
print(names.str.endswith('M'))
#isalnum() 是否字符数字字母
print(pd.Series([1,'A','2',3]).str.isalnum())
#isalpha() 是否字母
#isdigit() 是否数字
#isnumeric() 是否数字
#isdecimal() 是否decimal类型数字
#isspace() 是否space
#istitle() 是否标题
#islower() 是否小写
#isupper() 是否大写
#正则表达式方法
#是否匹配表达式
print(names.str.match('[a-z]+'))
#截取指定规则字符串
print(names.str.extract('(T.*)'))
#查找匹配规则字符串
print(names.str.findall('T.*'))
#替换指定规则字符串
print(names.str.replace('T.*','test'))
#contains,是否包含指定正则表达式字符串
print(names.str.contains('T'))
#count ,计数指定字符串出现次数
print(names.str.count('T.*'))
#splist, rsplit支持使用正则拆分
#字符串切片操作
#获取指定位置值
print(names.str[2])
#print(names.str.get(2))
#切片
print(names.str[0:3])
#print(names.str.slice(0,3))
#切片替换
print(names.str.slice_replace(0,3,'R'))
#连接字符串
print(names.str.join(sep=';'))
2.11Pandas处理时间序列
Pandas提供强大的时间索引数据处理工具。
时间戳:一个具体的时间
时间间隔,周期:一个时间区间
时间增量或持续时间:一个精确时间长度,比如多少秒
实例:
def pandas14():
'''
Pandas时间序列
:return:
'''
from datetime import datetime
#传入一个字符串,返回一个Timestamp对象
#传入一个字符列表,返回一个DatetimeIndex类型
date1 = pd.to_datetime('2022-10-23')
print(date1)
# 时间序列,to_datetime可以转换多种格式数据
date2 = pd.to_datetime(['2022-10-23','20210422','01-02-2024',datetime(2023,11,20)])
print(date2)
#通过DatetimeIndex对象的to_period,转换为PeriodIndex,处理时间间隔数据
date3 = date2.to_period('m')
print(date3)
#日期之间增量,Timedelta类型
date4 = date2 - date1
print(date4)
# 时间日期格式化
# %Y 年
# %m 月
# %B 月名
# %b 月名缩写
# %d 日
# %A 星期
# %a 星期缩写
# %H 时24小时
# %I 时12小时
# %p 上午,下午
# %S 秒
# %M 分
print(date1.strftime('%A'))
#创建时间序列索引
date_index = pd.DatetimeIndex(['2021-08-01','2021-08-02','2021-08-03','2021-08-04'])
df1 = pd.DataFrame({'data':[120,222,200,500]},index=date_index,columns=['data'])
print(df1)
#直接年月切片访问
print(df1['2021-08-01':'2021-08-03'])
#print(df1['2021'])
print(df1.loc['2021'])
#pd.date_range()处理时间戳
#pd.period_range()处理周期
#pd.timedelta_range()处理时间间隔
#时间日期列表
date5 = pd.date_range('2022-10-01','2022-12-31')
#创建一个月数据
#date5 = pd.date_range('2022-10-01',periods=31)
#创建8小时日期
#date5 = pd.date_range('2022-10-01',periods=8,freq='H')
print(date5)
#8个月周期
date6 = pd.period_range('2015-07',periods=8,freq='M')
print(date6)
#时间序列
date7 = pd.timedelta_range('00:00:00',periods=24,freq='H')
print(date7)
#freq偏移量对应代码
#D 天 ; B 工作日
#W 周
#M 月末 BM 工作日月末
#Q 季度末 BQ
#A 年末 BA
#H 小时 BH 工作时间
#T 分钟
#S 秒
#L 毫秒
#U 微秒
#N 纳秒
2.12Pandas eval()与query()
使用Pandas eval(),query()方法,提高数据集之间运算速度。
实例:
def pandas15():
'''
pandas eval(),query()方法
:return:
'''
rng = np.random.RandomState(2000)
df1 = pd.DataFrame(rng.rand(10000,10))
df2 = pd.DataFrame(rng.rand(10000,10))
df3 = pd.DataFrame(rng.rand(10000,10))
df_sum = pd.eval('df1+df2+df3')
df_sum1 = df1 + df2 + df3
#算术运算
df_cal1 = pd.eval('df1 - df2 * df3 / df1')
#比较运算
df_cal2 = pd.eval('(df1 > df2) & (df2 < df3)')
#位运算
df_cal3 = pd.eval('(df1 < 0.5) & (df2 > 0.5)')
#列间运算
df4 = pd.DataFrame(rng.rand(100000,4),columns=['a','b','c','d'])
df_cal4 = pd.eval('(df4.c + df4.a) / df4.c')
print(df_cal4)
#创建新列
df4.eval('e = a + b',inplace=True)
print(df4)
#query也可以计算代数式
n_min = 0.2
n_max = 0.3
#通过@使用局部变量
df_cal5 = df4.query('a < @n_min and b >@n_max')
print(df_cal5)