广告网站设计公司 作用外贸推广平台排名
pandas概述
pandas :pannel data analysis(面板数据分析)。pandas是基于numpy构建的,为时间序列分析提供了很好的支持。pandas中有两个主要的数据结构,一个是Series
,另一个是DataFrame
。
数据结构 Series
Series 类似于一维数组与字典(map)数据结构的结合。它由一组数据和一组与数据相对应的数据标签(索引index)组成。这组数据和索引标签的基础都是一个一维ndarray数组。可将index索引理解为行索引。
Series的表现形式为:索引在左,数据在右。
• 获取数据和索引:ser_obj.index
, ser_obj.values
• 预览数据:ser_obj.head(n)
, ser_obj.tail(n)
使用一维数组生成Series
import pandas as pd
from pandas import Series,DataFrameprint('用一维数组生成Series')
x=Series([1,2,3,4])
print(x)
"""
用一维数组生成Series
0 1
1 2
2 3
3 4
dtype: int64
"""
print(x.values) #[1 2 3 4]
print(x.index) #RangeIndex(start=0, stop=4, step=1)print('指定Series的index') #可将index理解为行索引
x=Series([1,2,3,4],index=['a','b','c','d'])
print(x)
"""
指定Series的index
a 1
b 2
c 3
d 4
dtype: int64
"""
print(x.index) #Index(['a', 'b', 'c', 'd'], dtype='object')
print(x['a']) # 通过行索引来取得元素值:1
x['d'] = 6 # 通过行索引来赋值print(x[['c','a','d']]) # 类似于numpy的花式索引
"""
c 3
a 1
d 6
dtype: int64
"""print(x[x>2]) # 类似于numpy的布尔索引,value>2
"""
c 3
d 6
dtype: int64
"""print('b' in x ) # 类似于字典的使用:是否存在该索引:True
print('e' in x ) # False
用字典生成Series
data={'a':1,'b':2,'d':3,'c':4}
x=Series(data)
print(x)
"""
a 1
b 2
d 3
c 4
dtype: int64
"""#使用字典生成Series,并指定额外的index,不匹配的索引部分数据为NaN
exindex=['a','b','c','e']
y=Series(data,index=exindex) # 类似替换索引
print(y)
"""
a 1.0
b 2.0
c 4.0
e NaN
dtype: float64
"""#Series相加,相同行索引相加,不同行索引则数值为NaN
print(x+y)
"""
a 2.0
b 4.0
c 8.0
d NaN
e NaN
dtype: float64
"""# 指定Series/索引的名字
y.name='weight of letters'
y.index.name='letter'
print(y)
"""
letter
a 1.0
b 2.0
c 4.0
e NaN
Name: weight of letters, dtype: float64
"""#替换index,不匹配的索引部分数据为NaN
y.index=['a','b','c','f']
print(y)
"""
a 1.0
b 2.0
c 4.0
f NaN
Name: weight of letters, dtype: float64
"""
数据结构 DataFrame
DataFrame是一个类似表格的数据结构,索引包括列索引和行索引,包含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)。DataFrame的每一行和每一列都是一个Series,这个Series的name属性为当前的行索引名/列索引名。
-
通过列索引获取列数据(Series类型 ):
df_obj[col_idx]
或df_obj.col_idx
-
.ix
,标签与位置混合索引
可输入给DataFrame构造器的数据:
DataFrame的使用代码示例:
import pandas as pd
from pandas import DataFrame,Series
import numpy as np#使用字典生成DataFrame,Key为列的名字
data={'state':['ok','ok','good','bad'],'year':[2000,2001,2002,2003],'pop':[3.7,3.6,2.4,0.9]}
print(DataFrame(data)) # 行索引index默认为0,1,2,3
"""state year pop
0 ok 2000 3.7
1 ok 2001 3.6
2 good 2002 2.4
3 bad 2003 0.9
"""#指定列索引columns,不匹配的列为NaN
print(DataFrame(data,columns=['year','state','pop','debt']))
"""year state pop debt
0 2000 ok 3.7 NaN
1 2001 ok 3.6 NaN
2 2002 good 2.4 NaN
3 2003 bad 0.9 NaN
"""#指定行索引 index
x=DataFrame(data,columns=['year','state','pop','debt'],index=['one','two','three','four'])
print(x)
"""year state pop debt
one 2000 ok 3.7 NaN
two 2001 ok 3.6 NaN
three 2002 good 2.4 NaN
four 2003 bad 0.9 NaN
"""#'DataFrame元素的索引与修改
print(x['state']) # 返回一个名为state的Series
"""
one ok
two ok
three good
four bad
Name: state, dtype: object
"""print(x.state) # 可直接用.进行列索引
"""
one ok
two ok
three good
four bad
Name: state, dtype: object
"""print(x.ix['three']) # 用.ix[]来区分[]进行行索引
"""
year 2002
state good
pop 2.4
debt NaN
Name: three, dtype: object
"""x['debt'] = 16.5 #修改一整列数据
print(x)
"""year state pop debt
one 2000 ok 3.7 16.5
two 2001 ok 3.6 16.5
three 2002 good 2.4 16.5
four 2003 bad 0.9 16.5
"""x.debt = np.arange(4) # 用numpy数组修改元素
print(x)
"""year state pop debt
one 2000 ok 3.7 0
two 2001 ok 3.6 1
three 2002 good 2.4 2
four 2003 bad 0.9 3
"""# 用Series修改元素,没有指定的默认数据用NaN
val=Series([-1.2, -1.5, -1.7, 0], index = ['one', 'two', 'five', 'six'])
x.debt = val #DataFrame 的行索引不变
print(x)
"""year state pop debt
one 2000 ok 3.7 -1.2
two 2001 ok 3.6 -1.5
three 2002 good 2.4 NaN
four 2003 bad 0.9 NaN
"""#给DataFrame添加新列
x['gain'] = (x['debt'] > 0) #如果debt大于0为True
print(x)
"""year state pop debt gain
one 2000 ok 3.7 -1.2 False
two 2001 ok 3.6 -1.5 False
three 2002 good 2.4 NaN False
four 2003 bad 0.9 NaN False
"""#列的名称
print(x.columns)
#Index(['year', 'state', 'pop', 'debt', 'gain'], dtype='object')#DataFrame转置
print(x.T)
"""one two three four
year 2000 2001 2002 2003
state ok ok good bad
pop 3.7 3.6 2.4 0.9
debt -1.2 -1.5 NaN NaN
gain False False False False
"""#使用切片初始化数据,未匹配的的数据为NaN
pdata={'state':x['state'][0:3],'pop':x['pop'][0:2]}
y=DataFrame(pdata)
print(y)
"""state pop
one ok 3.7
three good NaN
two ok 3.6
"""#指定索引和列的名称
#与Series的index.name相区分
y.index.name = '序号'
y.columns.name = '信息'
print(y)
"""
信息 state pop
序号
one ok 3.7
three good NaN
two ok 3.6
"""print(y.values)
"""
[['ok' 3.7]['good' nan]['ok' 3.6]]
"""
df.assign()
:指定新的列(如果列名已存在,则替换;如果不存在,在添加该列),返回一个新的 DataFrame,不对原始的 DataFrame 进行修改;
# 接收 lambda 型函数对象,
>> df = DataFrame({'A':range(1, 6), 'B':np.random.randn(5)})
>> df.assign(ln_A=lambda x: np.log(x.A))A B ln_A
0 1 0.456539 0.000000
1 2 1.022736 0.693147
2 3 -0.158207 1.098612
3 4 0.951304 1.386294
4 5 -1.024661 1.609438# 此时 df 本身并未发生任何改变;
>> df.assign(A = range(21, 26))A B
0 21 0.456539
1 22 1.022736
2 23 -0.158207
3 24 0.951304
4 25 -1.024661
set_index()
:将某列设置为索引列;
索引对象
pandas的索引对象负责管理轴标签和轴名称等。构建Series或DataFrame时,所用到的任何数组或其他序列的标签都会被转换成一个Index对象。 Index对象是不可修改的,Series和DataFrame中的索引都是Index对象。
from pandas import Index
from pandas import Series,DataFrame
import numpy as np#获取Index对象
x = Series(range(3),index= ['a','b','c'])
index = x.index
print(index) #Index(['a', 'b', 'c'], dtype='object')
print(index[0:2]) #Index(['a', 'b'], dtype='object')try:index[0] = 'd'
except:print("Index is immutable")"""
Index is immutable
"""#构造/使用Index对象'
index = Index(np.arange(3))
obj2 = Series([1.5,-2.5,0], index= index)
print(obj2)
"""
0 1.5
1 -2.5
2 0.0
dtype: float64
"""
print( obj2.index is index) #True#判断列/行索引是否存在
data= {'pop':{2.4, 2.9},'year':{2001, 2002}}x=DataFrame(data)
print(x)
"""pop year
0 {2.4, 2.9} {2001, 2002}
1 {2.4, 2.9} {2001, 2002}
"""print('pop' in x.columns) #True
print( 1 in x.index) #True
基本功能
对列/行索引重新指定索引(删除/增加:行/列):reindex函数
reindex的method选项:
#重新指定索引及NaN填充值
x= Series([4,7,5],index= ['a','b','c'])
y= x.reindex(['a','b','c','d'])
print(y)
"""
a 4.0
b 7.0
c 5.0
d NaN
dtype: float64
"""## fill_value 指定不存在元素NaN的默认值
print(x.reindex(['a','b','c','d']), fill_value = 0)
"""
a 4
b 7
c 5
d 0
dtype: int64
"""#新指定索引并指定填充NaN的方法
x=Series('blue','purple', index= [0,2])
print(x.reindex(range(4)),method='ffill')
'''
0 blue
1 blue
2 purple
3 purple
dtype: object
'''#对DataFrame重新指定行/列索引
x= DataFrame(np.arange(9).reshape(3,3),index= ['a','c','d'],columns=['A','B','C'])print(x)
'''A B C
a 0 1 2
c 3 4 5
d 6 7 8
'''x= x.reindex(['a', 'b', 'c', 'd'],method='bfill')
print(x)
'''A B C
a 0 1 2
b 3 4 5
c 3 4 5
d 6 7 8
'''#重新指定column
states=['A', 'B', 'C', 'D']
x.reindex(columns = states, fill_value= 0)
print(x)
'''A B C D
a 0 1 2 0
b 3 4 5 0
d 6 7 8 0
c 3 4 5 0
'''#????
print(x.ix[['a', 'b', 'd', 'c'], states])
'''A B C D
a 0 1 2 0
b 3 4 5 0
d 6 7 8 0
c 3 4 5 0
'''
删除(丢弃)整一行/列的元素:drop函数
from pandas import Index
from pandas import Series,DataFrame
import numpy as np
import pandas as pd#Series根据行索引删除行
x= Series(np.arange(4),index= ['a','b','c','d'])
print(x.drop('c'))
'''
a 0
b 1
d 3
dtype: int32
'''# 花式删除
print(x.drop(['a','b']))
'''
c 2
d 3
dtype: int32
'''#DataFrame根据索引行/列删除行/列
x = DataFrame(np.arange(16).reshape((4, 4)),index = ['a', 'b', 'c', 'd'],columns = ['A', 'B', 'C', 'D'])print(x)
'''A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
'''print(x.drop(['A','B'],axis= 1)) # 在列的维度上删除AB两行
'''C D
a 2 3
b 6 7
c 10 11
d 14 15
'''print(x.drop('a',axis= 0)) # 在行的维度上删除行
'''A B C D
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
'''print(x.drop(['a','b'],axis= 0))
'''A B C D
c 8 9 10 11
d 12 13 14 15
'''