pandas教程:series和dataframe
原文链接:blog.ouyangsihai.cn >> pandas教程:series和dataframe
pandas是一种Python数据分析的利器,是一个开源的数据分析包,最初是应用于金融数据分析工具而开发出来的,因此pandas为时间序列分析提供了很好的支持。pandas是PyData项目的一部分。
官网: http://pandas.pydata.org/
官方文档: http://pandas.pydata.org/pandas-docs/stable/安装与导入
Python的Anaconda发行版,已经安装好pandas库,不需要另外安装
使用Anaconda界面安装,选择对应的pandas进行勾选安装即可
使用Anaconda命令安装:conda install pandas
使用PyPi安装命令安装:pip install pandas
from pandas import Series, DataFrame import pandas as pd
Pandas的数据类型
Pandas基于两种数据类型: series 与 dataframe 。
Series:一种类似于一维数组的对象,是由一组数据(各种NumPy数据类型)以及一组与之相关的数据标签(即索引)组成。仅由一组数据也可产生简单的Series对象。注意:Series中的索引值是可以重复的。
DataFrame:一个表格型的数据结构,包含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔型等),DataFrame即有行索引也有列索引,可以被看做是由Series组成的字典。Series
一个series是一个一维的数据类型,其中每一个元素都有一个标签。类似于Numpy中元素带标签的数组。其中,标签可以是数字或者字符串。
series属性 data = np.array(['a','b','c','d']) # ser02 = pd.Series(data,index=[100,101,102,103]) ser02 = pd.Series(data,index=['name','age','sex','address']) ser020 a 1 b 2 c 3 d dtype: object name a age b sex c address d dtype: object
从字典创建一个系列
字典(dict)可以作为输入传递,如果没有指定索引,则按排序顺序取得字典键以构造索引。 如果传递了索引,索引中与标签对应的数据中的值将被拉出。
data = {'a':1,'b':2,'c':3} ser03 = pd.Series(data) ser03 #指定索引 data = {'a':1,'b':2,'c':3} ser03 = pd.Series(data,index = ['a','b','c','d']) ser03 #标量创建 ser04 = pd.Series(5,index = [0,1,2,3]) ser04
a 1 b 2 c 3 dtype: int64 a 1.0 b 2.0 c 3.0 d NaN dtype: float64 0 5 1 5 2 5 3 5 dtype: int64
Series值的获取
Series值的获取主要有两种方式:
通过方括号+索引的方式读取对应索引的数据,有可能返回多条数据 通过方括号+下标值的方式读取对应下标值的数据,下标值的取值范围为:[0,len(Series.values));另外下标值也可以是负数,表示从右往左获取数据 Series获取多个值的方式类似NumPy中的ndarray的切片操作,通过方括号+下标值/索引值+冒号(:)的形式来截取series对象中的一部分数
#引入模块 import pandas as pd import numpy as np #检索第一个元素。 ser05 = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) print(ser05[1]) print(ser05['a']) print(ser05['d'])
#检索系列中的前三个元素 ser05 = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) #通过索引来获取数据 print(ser05[:3]) print(ser05[::2]) print(ser05[4:2:-1]) #通过标签(下标值)来获取数据 print(ser05['b':'d']) ser05['a':'d':2] ser05['e':'c':-1] ser05[['a','b']]
a 1 b 2 c 3 dtype: int64 a 1 c 3 e 5 dtype: int64 e 5 d 4 dtype: int64 b 2 c 3 d 4 dtype: int64 a 1 b 2 dtype: int64
Series的运算
#引入模块 import pandas as pd import numpy as np series = pd.Series({'a':941,'b':431,'c':9327}) series #输出大于500的值 series[series>500] series+10 series-100 series*10 #两个系列相加 ser01 = pd.Series([1,2,3]) ser02 = pd.Series([4,5,6]) ser01+ser02 #)计算各个元素的指数e的x次方 e 约等于 2.71828 np.exp(series) np.abs(series) #sign()计算各个元素的正负号: 1 正数,0:零,-1:负数 np.sign(series)
Series自动对齐
当多个series对象之间进行运算的时候,如果不同series之间具有不同的索引值,那么运算会自动对齐不同索引值的数据,如果某个series没有某个索引值,那么最终结果会赋值为NaN。
#引入模块 import pandas as pd import numpy as np serA = pd.Series([1,2,3],index = ['a','b','c']) serB = pd.Series([4,5,6],index = ['b','c','d']) print('---------serA+serB---------') print(serA) serA+serB
---------serA+serB--------- a 1 b 2 c 3 dtype: int64 a NaN b 6.0 c 8.0 d NaN dtype: float64
Series及其索引的name属性
Series对象本身以及索引都具有一个name属性,默认为空,根据需要可以进行赋值操作
DataFrame
一个dataframe是一个二维的表结构。Pandas的dataframe可以存储许多种不同的数据类型,并且每一个坐标轴都有自己的标签。你可以把它想象成一个series的字典项。
dataFrame属性
属性或方法 dates =pd.date_range('20130101', periods=6) print(type(dates)) #创建Dataframe,其中 index 决定索引序列,columns 决定列名 df =pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) print(df)<class 'pandas.core.indexes.datetimes.DatetimeIndex'> A B C D 2013-01-01 0.406575 -1.356139 0.188997 -1.308049 2013-01-02 -0.412154 0.123879 0.907458 0.201024 2013-01-03 0.576566 -1.875753 1.967512 -1.044405 2013-01-04 1.116106 -0.796381 0.432589 0.764339 2013-01-05 -1.851676 0.378964 -0.282481 0.296629 2013-01-06 -1.051984 0.960433 -1.313190 -0.093666
字典创建 DataFrame
df2 =pd.DataFrame({'A' : 1., 'B': pd.Timestamp('20130102'), 'C': pd.Series(1,index=list(range(4)),dtype='float32'), 'D': np.array([3]*4,dtype='int32'), 'E': pd.Categorical(["test","train","test","train"]), 'F':'foo' }) print(df2)
A B C D E F 0 1.0 2013-01-02 1.0 3 test foo 1 1.0 2013-01-02 1.0 3 train foo 2 1.0 2013-01-02 1.0 3 test foo 3 1.0 2013-01-02 1.0 3 train foo
从列表创建DataFrame
data = [1,2,3,4] df02 = pd.DataFrame(data) 0 1 1 2 2 3 3 4
从列表字典来创建DataFrame
data = {'Name':['Tom','Jack','Steve'],'Age':[19,18,20]} # df04 = pd.DataFrame(data) #指定行索引和列索引 df04 = pd.DataFrame(data,index = ['rank1','rank2','rank3'],columns = ['Name','Age','Sex'])
Name Age Sex rank1 Tom 19 NaN rank2 Jack 18 NaN rank3 Steve 20 NaN
从字典列表创建数据帧DataFrame
data = [{'a':1,'b':2},{'a':1,'b':2,'c':3}] # df05 = pd.DataFrame(data) #传递字典列表指定行索引 # df05 = pd.DataFrame(data,index = ['first','second']) #传递字典列表指定行索引,列索引 df05 = pd.DataFrame(data,index = ['first','second'],columns = ['a','b','c','d'])
a b c d first 1 2 NaN NaN second 1 2 3.0 NaN
从系列的字典来创建DataFrame
data = { 'one':pd.Series([1,2,3],index = ['a','b','c']), 'two':pd.Series([1,2,3,4],index = ['a','b','c','d']) df06 = pd.DataFrame(data)
one two a 1.0 1 b 2.0 2 c 3.0 3 d NaN 4
dataFrame数据操作
#直接通过列索引来获取某一列的值 data = { 'one':pd.Series([1,2,3],index = ['a','b','c']), 'two':pd.Series([1,2,3,4],index = ['a','b','c','d']) df06 = pd.DataFrame(data) df06['one'] # df06.one # df06.ix[:,'one'] # df06.loc[:,'one'] # df06.iloc[:,0]
data = { 'one':pd.Series([1,2,3],index = ['a','b','c']), 'two':pd.Series([1,2,3,4],index = ['a','b','c','d']) df06 = pd.DataFrame(data) df06['three'] = pd.Series([10,20,30],index = ['a','b','c'])
#直接通过列名进行修改 df06['three'] = [7,8,9,10]
data = { 'one':pd.Series([1,2,3],index = ['a','b','c']), 'two':pd.Series([1,2,3,4],index = ['a','b','c','d']), 'three':pd.Series([10,20,30],index = ['a','b','c']) df06 = pd.DataFrame(data) #使用del删除列 # del(df06['three']) #使用pop删除 df06.pop('two')
data = { 'one':pd.Series([1,2,3],index = ['a','b','c']), 'two':pd.Series([1,2,3,4],index = ['a','b','c','d']), 'three':pd.Series([10,20,30],index = ['a','b','c']) df06 = pd.DataFrame(data) #可以通过将行标签传递给loc函数或者ix函数来选择行 # df06.loc['a'] df06.loc[:,'two'] # df06.ix['a'] # 按整数位置选择 # 可以通过将整数位置传递给iloc函数来选择行。参考以下示例代码 - df06.iloc[2] # 行切片 # 可以使用:运算符选择多行。参考以下示例代码 - df06[2:4]
# df06.ix['e'] = [22,33,444] df06.loc['e'] = [22,33,444] # 添加加行 # 使用append()函数将新行添加到DataFrame。 此功能将附加行结束。 #创建一行数据 # data2 = pd.DataFrame([{'one':22,'two':33,'three':44}],index = ['e']) data2 = pd.DataFrame([[22,33,44]],columns = ['one','two','three'],index = ['f']) # data2 df06 = df06.append(data2)
df06 = df06.drop('e')
文章有不当之处,欢迎指正,如果喜欢微信阅读,你也可以关注我的微信公众号:
cplus人工智能算法后端技术
,获取优质学习资源。