import pandas as pd
import numpy as np
5.1 pandas数据结构介绍
"""
Series:一维的数组型对象,索引 值
"""
obj = pd.Series([4,7,-5,3])
print(obj)
print(obj.dtype)
print(obj.values)
print(obj.index)
"""创建一个索引序列,用标签表示每个数据点"""
obj2 = pd.Series([4,7,-5,3],index=['d','b','a','c'])
print(obj2)
print(obj2.dtype)
print(obj2.index)
"""---用标签进行索引---"""
print(obj2['a'])
print(obj2['d'] ==6)
print(obj2[['c','a','d']])
"""布尔值进行过滤"""
print(obj2[obj2 > 0])
"""与标量相乘"""
print(obj2*2)
"""应用数学函数"""
print(np.exp(obj2))
"""使用一个字典生成一个Series"""
sdata = {
'Oh':3500,'Te':7100,'Hm':1600,'Yu':5000}
obj3 = pd.Series(sdata)
print(obj3)
states = {
'Ca','Oh','Te','Hm','Yu'}
obj4 = pd.Series(sdata,index=states)
print(obj4)
"""使用isnull和ntnull函数见检查缺失是数据"""
print(pd.isnull(obj4))
print(pd.notnull(obj4))
print(obj4.isnull())
"""自动对齐索引"""
print(obj3)
print(obj4)
print(obj3+obj4)
"""Sreies对象的name属性"""
obj4.name = 'population'
obj4.index.name = 'state'
print(obj4)
"""通过按位置复制改变Series的索引"""
print(obj)
obj.index = ['Bob','Cat','Jone','Mak']
print(obj)
在这里插入代码片
"""
DataFrame:矩阵的数据表,
包含已排列的列集合,有行索引和列索引
数据被存储为一个以上的二维块
"""
data = {
'state':['O','O','O','N','N','N'],
'year':[2000,2001,2002,2001,2002,2003],
'pop':[1.5,1.7,3.6,2.4,2.9,3.2]}
frame = pd.DataFrame(data)
print(frame)
print(frame.head())
print(pd.DataFrame(data,columns=['year','state','pop']))
frame2 = pd.DataFrame(data,columns=['year','state','pop','debt'],
index = ['one','two','three','four','five','six'])
print(frame2)
"""DataFrame的其中一列可以按字典标记或属性那样检索为Series"""
print(frame2['state'])
print(frame2.year)
"""属性loc进行行选取"""
print(frame2.loc['three'])
"""修改列的引用"""
frame2['debt'] = np.arange(6)
print(frame2)
"""将Series赋值给一列时,Series的索引将会按照DataFrame的索引重新排列,并在空缺的地方填充缺失值"""
val = pd.Series([-1.2,-1.5,-1.7], index=['two','four','five'])
frame2['debt'] = val
print(frame2)
frame2['eastern'] = frame2.state == 'O'
print(frame2)
"""del关键字删除列"""
del frame2['eastern']
print(frame2.columns)
"""
DataFrame选取的列是数据的视图,而不是拷贝
对Series的修改会映射到DataFrame中
需要肤质使用copy方法
"""
print("\n")
"""数据形式为包含字典的嵌套字典"""
pop = {
'Ne':{
2001:2.4,2002:2.9},
'Oh':{
2000:1.5,2001:1.7,2002:3.6}}
frame3 = pd.DataFrame(pop)
print(frame3)
print(frame3.T)
print(pd.DataFrame(pop, index=[2001,2002,2003]))
"""---包含Series的字典用于构造DataFrame---"""
pdata = {
'Oh':frame3['Oh'][:-1],
'Ne':frame3["Ne"][:2]}
print("\n")
print(pd.DataFrame(pdata))
在这里插入代码片
"""
Pandas索引对象是用于存储标签和其他元数据的
索引对象具有不变性
索引对象可以包含重复的标签
"""
obj = pd.Series(range(3),index=['a','b','c'])
index = obj.index
print(index)
print(index[1:])
labels = pd.Index(np.arange(3))
obj2 = pd.Series([1.5,-2.5,0],index=labels)
print(obj2.index is labels)
print(frame3)
print('Oh'in frame3.columns)
print(2003 in frame3.index)
在这里插入代码片
5.2 基本功能
"""
reindex方法可以改变行索引、列索引
reindex(index,method,fill_value,limit,tolerance,level,copy)
"""
s = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d','d','a','c'])
print(s)
s1 = s[~s.index.duplicated()]
print(s1.reindex(index=['a','b','c','d']))
obj3 = pd.Series(['b','p','y'],index=[0,2,4])
print(obj3)
print(obj3.reindex(range(6),method='ffill'))
frame = pd.DataFrame(np.arange(9).reshape((3, 3)),
index=['a','c','d'],
columns=['Oh','Te','Ca'])
print(frame)
states = ['Tw','Ua','Ca']
frame2 = frame.reindex(index=['a','b','c','d'],
columns=states)
"""使用loc"""
在这里插入代码片
"""
drop方法返回一个含有指示值或轴向上删除值的新对象
在DataFrame中,drop可根据行标签删除值,axis从列中删除值,
drop会修改Series,DateFrame的尺寸或形状,这些方法直接操作原对象,不反回新的值
"""
obj = pd.Series(np.arange(5.),index=['a','b','c','d','e'])
print(obj)
new_obj = obj.drop('c')
print(new_obj)
print(obj.drop('c',inplace=True))
data = pd.DataFrame(np.arange(16).reshape((4,4)),
index=['Oh','Co','Ut','Ne'],
columns=['one','two','three','four'])
print(data)
print(data.drop(['Co','Oh']))
print(data.drop('two',axis=1))
print(data.drop(['two','four'],axis='columns'))
在这里插入代码片
"""
Series的索引可以不仅仅是整数
Series的切片包含尾部
DataFrame使用单个值或序列,可以索引出一个或多个列
"""
obj = pd.Series(np.arange(4.),index=['a','b','c','d'])
print(obj)
print(obj['b'])
print(obj[1])
print(obj[['b','a','d']])
print(obj[[1,3]])
print(obj[obj<2])
print(obj['b':'c'])
obj['b':'c'] = 5
print(obj)
data = pd.DataFrame(np.arange(16).reshape((4,4)),
index=['Oh','Co','Ut','Ne'],
columns=['one','two','three','four'])
print(data)
print(data['two'])
print(data[['three','one']])
print(data[:2])
print(data[data['three']>5])
print(data<5)
data[data<5]=0
print(data)
"""
DataFrame使用loc和iloc运算符分别用于严格处理基于标签和基于整数的索引
"""
data = pd.DataFrame(np.arange(16).reshape((4,4)),
index=['Oh','Co','Ut','Ne'],
columns=['one','two','three','four'])
print("\n")
print(data)
print(data.loc['Co',['two','three']])
print(data.iloc[2,[3,0,1]])
print(data.iloc[2])
print(data.iloc[[1,2],[3,0,1]])
"""索引功能用于切片"""
print(data.loc[:'Ut','two'])
print(data.iloc[:,:3][data.three>5])
在这里插入代码片
"""
为了保持一致性,数据选择使用标签索引(loc和iloc)
"""
ser = pd.Series(np.arange(3.))
print(ser.loc[:1])
print(ser.iloc[:1])
在这里插入代码片
"""
将对象相加时,如果讯在某个索引对不相同,则返回结果的索引将是索引对的并集
没有交叠的标签位置上,内部数据对齐会产生缺失值
DataFrame的实例中,行和列都会执行对齐
将两个行和列完全不同的DataFrame对象相加,结果全部为空
"""
s1 = pd.Series([7.3,-2.5,3.4,2.5],index=['a','c','d','e'])
s2 = pd.Series([-2.1,3.6,-1.5,4,3.1],
index=['a','c','e','f','g'])
print(s1)
print(s2)
print(s1+s2)
df1 = pd.DataFrame(np.arange(9).reshape((3,3)),
columns=list('bcd'),
index=['Oh','Te','Co'])
df2 = pd.DataFrame(np.arange(12).reshape((4,3)),
columns=list('bde'),
index=['Ut','Oh','Te','Or'])
print(df1)
print(df2)
print(df1+df2)
"""
将两个行和列完全不同的DataFrame对象相加,结果全部为空
"""
df1 = pd.DataFrame({
'A':[1,2]})
df2 = pd.DataFrame({
'B':[3,4]})
print(df1)
print(df2)
print(df1-df2)
"""
add,radd
sub,rsub
div,rdiv
floordiv,rfloordiv整除
mul,rmul 乘法
pow,rpow幂次方
"""
df1 = pd.DataFrame(np.arange(12.).reshape((3,4)),
columns=list('abcd'))
df2 = pd.DataFrame(np.arange(20.).reshape((4,5)),
columns=list('abcde'))
df2.loc[1,'b'] = np.nan
print(df1)
print(df2)
print(df1+df2)
"""
def1使用add方法,将d2和一个fill_value作为参数传入
"""
print(df1.add(df2,fill_value=0))
print(df1.add(df2,fill_value=0)+df2)
print(1/df1)
print(df1.rdiv(1))
print(df1.reindex(columns=df2.columns,fill_value=0))
"""
将Series的索引和DataFrame的列进行匹配,并广播到各行
索引值不在DataFrame的列中,也不在Series的索引中,对象会重建索引形成联合
"""
arr = np.arange(12.).reshape((3,4))
print(arr)
print(arr[0])
print(arr-arr[0])
frame = pd.DataFrame(np.arange(12.).reshape((4,3)),
columns=list('bde'),
index=['Ut','Oh','Te','Or'])
series = frame.iloc[0]
print(frame)
print(series)
print(frame-series)
series2 = pd.Series(range(3),index=['b','e','f'])
print("\n")
print(series2)
print(frame)
print(frame+series2)
"""
在列上进行广播,在行上进行匹配
"""
series3 = frame['d']
print(frame)
print(series3)
print(frame.sub(series3,axis='index'))
在这里插入代码片
frame = pd.DataFrame(np.random.randn(4,3),
columns=list('bde'),
index=['Ut','Oh','Te','Or'])
print(frame)
print(np.abs(frame))
f = lambda x: x.max() - x.min()
print(frame.apply(f))
print(frame.apply(f, axis='columns'))
def f(x):
return pd.Series([x.min(),x.max()],index=['min','max'])
print(frame.apply(f))
"""
applymap方法:根据frame中的每个浮点数计算一个格式化字符串
"""
format = lambda x: '%.2f'%x
print(frame.applymap(format))
print(frame['e'].map(format))
在这里插入代码片
"""
排序
sort_index方法:按行或列索引惊醒字典型排序,返回一个新的,排序好的对象
sort_values方法: 根据Series的值进行排序,缺失值会排在尾部
DataFrame排序使用一列或多列作为排序键盘,选用参数by
"""
obj = pd.Series(range(4),index=['d','a','b','c'])
print("\n")
print(obj.sort_index())
frame = pd.DataFrame(np.arange(8).reshape((2,4)),
index=['three','one'],
columns=['d','a','b','c'])
print("\n")
print(frame)
print("\n")
print(frame.sort_index())
print(frame.sort_index(axis=1))
print(frame.sort_index(axis=1,ascending=False))
obj = pd.Series([4,7,-3,2])
print(obj.sort_values())
obj = pd.Series([4,np.nan,7,np.nan,-3,2])
print(obj.sort_values())
frame = pd.DataFrame({
'b':[4,7,-3,2],'a':[0,1,0,1]})
print("\n")
print(frame)
print(frame.sort_values(by='b'))
print(frame.sort_values(by=['a','b']))
""""
排名是值数组从1到有效数据点总数分配名次的操作
rank方法:通过平均排名分配到每个组来打破平级关系
"""
#text01
obj = pd.Series([7,-5,7,4,2,0,4])
print(obj.rank())
print("\n")
print(obj.rank(method='first'))#根据数据中的观察数据排名
print("\n")
print(obj.rank(ascending=False,method='max'))
frame = pd.DataFrame({
'b':[4.3,7,-3,2],
'a':[0,1,0,1],
'c':[-2,5,8,-2.5]})
print(frame)
print(frame.rank(axis='columns'))
在这里插入代码片
"""
带有重复标签的索引索格条目返回一个序列,单个条目返回标量值
"""
在这里插入代码片
5.3 描述性统计的概述与计算
df = pd.DataFrame([[1.4,np.nan],[7.1,-4.5],
[np.nan,np.nan],[0.75,-1.3]],
index=['a','b','c','d'],
columns=['one','two'])
print(df)
print(df.sum())
print(df.sum(axis='columns'))
print(df.mean(axis='columns',skipna=False))
在这里插入代码片
import pandas_datareader.data as web
在这里插入代码片
"""
Series的unique方法,给出唯一值
value_counts:计算Series包含的值的个数
isin:执行向量化的成员属性检查
"""
obj = pd.Series(['1','1','2','2','3','3','3','3','3'])
uniques = obj.unique()
print("\n")
print(uniques)
print(obj.value_counts())
mask = obj.isin(['2','3'])
print("\n")
print(mask)
在这里插入代码片