from pandas import Series,DataFrame
import pandas as pd
import numpy as np
行用0,列用1
(一) Series
一种类似一维数组的对象,由一组数据(各种numpy数据类型)以及一组与之相关的数据标签(即索引)组成
1.创建series
Obj1=Series([1,2,3,4]) [结果] 0 1 1 2 2 3 3 4 dtype: int64 |
#指定索引的情况 [结果] one 1 two 2 three 3 four 4 dtype: int64 值 [1 2 3 4] 值类型 <class 'numpy.ndarray'> 索引 Index(['one', 'two', 'three', 'four'], dtype='object') 索引类型 <class 'pandas.core.indexes.base.Index'> |
sdata={'Ohio':35000,'Texas':71000,'Oregon':16000,'Utah':5000} obj3=Series(sdata) 【结果】 Ohio 35000 Oregon 16000 Texas 71000 Utah 5000 dtype: int64 |
states=['California','Ohio','Texas','Oregon','Utah'] obj4=Series(sdata,index=states) 【结果】 California NaN Ohio 35000.0 Texas 71000.0 Oregon 16000.0 Utah 5000.0 dtype: float64 |
2.索引
索引取值 print(obj3['Ohio']) |
Numpy数组运算(布尔运算、标量乘法、数学函数)等,保留对于索引和值得对应关系 Series利用标签的切片运算与普通的Python切片运算不同,其末端是包含的 |
算数运算中自动对齐索引 print(obj3+obj4) 【结果】 California NaN Ohio 70000.0 Oregon 32000.0 Texas 142000.0 Utah 10000.0 dtype: float64 |
Series及索引命名 obj5.name='popultion' 【结果】 state California NaN Ohio 70000.0 Oregon 32000.0 Texas 142000.0 Utah 10000.0 Name: popultion, dtype: float64 |
索引可以就地修改 obj1.index=['aaa','bbb','ccc','ddd'] 【结果】 aaa 1 bbb 2 ccc 3 ddd 4 dtype: int64 |
3.缺失数据
NaN表示缺失数据
Obj.isnull()返回布尔型
(二) DataFrame
DataFrame中的数据是以一个或多个二维块存放的
DataFrame 面向行和面向列的操作基本是平衡的,任意抽出一列都是 Series。
1.创建
直接传入一个等长列表或者NumPy数组组成的字典
data={'state':['California','Ohio','Texas','Oregon','Utah'], 【结果】 POP Year state 0 1.0 2001 California 1 2.1 2001 Ohio 2 1.5 2002 Texas 3 1.8 2001 Oregon 4 2.5 2000 Utah #以二维数组的形式返回值 [[1.0 2001 'California'] [2.1 2001 'Ohio'] [1.5 2002 'Texas'] [1.8 2001 'Oregon'] [2.5 2000 'Utah']] RangeIndex(start=0, stop=5, step=1) Index(['POP', 'Year', 'state'], dtype='object') |
frame2=DataFrame(frame,columns=['Year','state','POP','debt']) 【结果】 Year state POP debt 0 2001 California 1.0 NaN 1 2001 Ohio 2.1 NaN 2 2002 Texas 1.5 NaN 3 2001 Oregon 1.8 NaN 4 2000 Utah 2.5 NaN |
2.索引
(1)获取列
通过字典表记或者属性方式获取列,返回得是Series,拥有与原DataFrame相同的索引,且name属性也已经设置好.索引方式返回的只是视图,任何修改都会影响原数据(就地修改)
dataState=frame['state'] 【结果】 字典标记 0 California 1 Ohio 2 Texas 3 Oregon 4 Utah Name: state, dtype: object 数据类型 <class 'pandas.core.series.Series'> names属性 state 属性 0 2001 1 2001 2 2002 3 2001 4 2000 Name: Year, dtype: int64 数据类型 <class 'pandas.core.series.Series'> |
obj[val]选取DataFrame的单个列或一组列。布尔型数组(过滤行),切片(行切片),布尔型DataFrame(根据条件设置值),通过切片索引或布尔型数组获得的是行 |
obj.ix[]选取单个行或者一组行,通过ix切片的索引末端也是包含的 |
(2)获取行
print(frame.ix[0]) 【结果】 POP 1 Year 2001 state California Name: 0, dtype: object |
(3)赋值
# 可以赋值标量 【结果】 Year state POP debt 0 2001 California 1.0 6 1 2001 Ohio 2.1 6 2 2002 Texas 1.5 6 3 2001 Oregon 1.8 6 4 2000 Utah 2.5 6 |
# 可以赋一组值,长度需一致 【结果】 Year state POP debt 0 2001 California 1.0 0 1 2001 Ohio 2.1 1 2 2002 Texas 1.5 2 3 2001 Oregon 1.8 3 4 2000 Utah 2.5 4 |
# 可以赋值数组,长度需一致 【结果】 Year state POP debt 0 2001 California 1.0 0 1 2001 Ohio 2.1 1 2 2002 Texas 1.5 2 3 2001 Oregon 1.8 3 4 2000 Utah 2.5 4 |
# 可以赋值Series序列,并且索引对应,否则值为NA 【结果】 Year state POP debt 0 2001 California 1.0 NaN 1 2001 Ohio 2.1 4.0 2 2002 Texas 1.5 3.0 3 2001 Oregon 1.8 NaN 4 2000 Utah 2.5 5.0 |
# 不存在的值创造出新的列 【结果】 Year state POP debt area 0 2001 California 1.0 NaN 100 1 2001 Ohio 2.1 4.0 200 2 2002 Texas 1.5 3.0 300 3 2001 Oregon 1.8 NaN 400 4 2000 Utah 2.5 5.0 500 |
(4)删除列
print(frame2.columns) 【结果】 Index(['Year', 'state', 'POP', 'debt', 'area'], dtype='object') Index(['Year', 'state', 'POP', 'debt'], dtype='object') |
# 只需要传入数据或者列表,即可删除指定值,返回除删除指定值以外的新对象 frame=DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'], |
# dataframe可删除任意轴上的索引值,如果删除得是列,需要加参数axis=1,默认是0 print('删除Ohio列') |
(5)就地修改
dd=frame2['POP'].copy() 【结果】 6 Year state POP debt 0 2001 California 1.0 NaN 1 2001 Ohio 2.1 4.0 2 2002 Texas 1.5 3.0 3 2001 Oregon 1.8 NaN 4 2000 Utah 2.5 5.0 |
frame2['POP']=range(5) 【结果】 Year state POP debt 0 2001 California 0 NaN 1 2001 Ohio 1 4.0 2 2002 Texas 2 3.0 3 2001 Oregon 3 NaN 4 2000 Utah 4 5.0 |
(6)嵌套字典(字典中的字典)
不指定的话,会默认外层字典中的键为列索引,内层字典中的键为行索引
china={'beijing':{'food':'RoastDuck','place':'GreatWall','people':'DaMimi'}, 【输出】 anhui beijing shanghai food doufu RoastDuck baozi people baozheng DaMimi sunli place yellowMountain GreatWall dongfangmignzhu |
(三)重新索引
Series对象的重新索引通过 reindex(index,method="ffill"/"bfill",fill_value=str)实现 其中,.reindex() 方法会返回一个新对象,其 index 严格遵循给出的参数,method:{'backfill', 'bfill', 'pad', 'ffill', None} 参数用于指定插值(填充)方式,当没有给出时,自动用 fill_value 填充,默认为 NaN(ffill = pad,bfill = back fill,分别指插值时向前还是向后取值) | |
DataFrame 对象的重新索引方法为:.reindex(index=None,columns=None,**kwargs)。 可同时对行、列重新索引,只不过插值方法method 参数只能应用于行,即轴 0。 | |
frame=DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'], columns=['Ohio','Texas','Newyork']) 当只传入一个参数时,用于重新索引行 frame12=frame.reindex(columns=['Ohio','Texas','California','Newyork']) print frame12 Ohio Texas California Newyork a 0 1 NaN 2 b 3 4 NaN 5 c 6 7 NaN 8 d 9 10 NaN 11 使用columns 关键字参数,用于给列索引。 frame13=frame.reindex(['a','c','b','d','e'], columns=['Ohio','Texas','California','Newyork']) print frame13 Ohio Texas California Newyork a 0 1 NaN 2 c 6 7 NaN 8 b 3 4 NaN 5 d 9 10 NaN 11 e NaN NaN NaN NaN | |
d1.ix[['a','c','b','d','e'], ['Ohio','Texas','California','Newyork']] #使用ix效果和上面相同 |
(四)算数运算和数据对齐
Series运算,自动对齐,不重叠的部分引入NaN值;DataFrame的操作会同时发生在行和列上 |
DataFrame和Series之间的算数运算会将Series索引匹配到DataFrame的列,然后沿着行一直向下传播,如果希望是匹配行且在列上广播,则可调用frame.sub(ser,aixs=0) |
(五)排序和排名
1. 排序
对行或者列的索引进行排序,可以使用sort_index()方法;dataFrame.sort_index()默认是按行索引排序,如果加参数sort_index(axis=1),则为按列索引排序;默认是升序的,也可以通过加参数sort_index(ascending=False)降序排列 |
如果要按值对series进行排序,则可以使用order()方法,任何缺失值默认值都会被放在末尾;dataFrame.sort_index(by=一个或多个列名)按值排序 |
2.排名
obj=Series([7,-5,7,4,2,0,4]) obj.rank(method='first',ascending=False) #按值在原始数据中的出现顺序排名 obj.rank(method='max') #使用整个组的排名最大 frame=DataFrame({'b':[4.3,7,-3,2],'a':[0,1,0,1],'c':[-2,5,8,-2.5]}) frame.rank(axis=1) #使用列排名 print obj.rank(method='min')#使用整个组的排名最小 print obj.rank(method='average')#默认:在相等分组中,为各个值分配平均排名 |
(六)汇总和描述计算统计
用于从series中提取一个值(均值、总和)或者从dataFrame中提取series,前提都是没有缺失数据。
dataFrame.mean/sum/var/std/median/mad(axis,skipna,level)求均值/和/方差/标准差/中位数/平均绝对离差
dataFrame.count()非na的个数
axis用于约简的轴,默认是0即约简行,也就是按列求和、求均值;axis=1,约简列,即按行求和求均值;
skipna,默认为Ture,跳过缺失值,当它不存在,设为False的话,有缺失值就返回na;
Level,层次化索引,根据level约简
dataFrame.idmax/idmin()返回最大值最小值的索引
dataFrame.cumsum()累计求和
dataFrame.describe()产生多个汇总统计(针对列)
isin()、value_counts、unique
(七)处理缺失数据
Na处理方法 | |
dropna | 过滤缺失数据,对于DataFrame类型,默认是过虑掉任何含有缺失值的行,加入参数how='all'就是过滤掉全是NA的行,传入axis=1则丢弃相关列,另外一个有趣的参数是 thresh,该参数的类型为整数,它的作用是,比如 thresh=3,会在一行中至少有 3 个非 NA 值时将其保留。 |
fillna | 用指定值或差值方法填充缺失数据(ffill前向填充, bfill后向填充) |
isnull | 返回一个含有布尔值的对象,这些布尔值表示哪些值是缺失值/NA |
notnull | isnull的否定式 |
填充缺失数据 | ||
fillna()
| VALUE | 参数为常数,则缺失值替换为常数 |
字典,实现对不同列填充不同的值,例;print(df.fillna({0:"ling",2:"贰"})),分别对第一列和第三列的值进行填充 | ||
inplace | 默认返回新对象,若想直接填充原对象,加参数inplace=True | |
method | 插值方式,默认ffill | |
axis | 待填充的轴,默认为0 | |
limit | 可以填充的最大数量 |
(八) 层次化索引
1.建立层次化索引
col=MultiIndex.from_arrays([['China','China','China','USA'],['BEIJING','ANHUI','SHANGHAI','NEWYORK']],names=['Country','City']) 【结果】 Country China USA City BEIJING ANHUI SHANGHAI NEWYORK industry class technology Semiconductor 0 1 2 3 High-speed rail 4 5 6 7 Serviece Tourism 8 9 10 11 Agriculture Vegetables 12 13 14 15 |
Swaplevel(a,b)a和b可以是编号,也可以是名称,交换a、b,并返回交换后的新对象,数据不变 |
Sorlevel(a)根据a级别中的值进行排序 |
2.根据级别汇总统计
# 按列索引求和 print(data.sum(level='Country',axis=1)) #按行索引求和 print(data.sum(level='class')) |
2. 使用DataFrame的列
# 将层次化索引转到列中 【结果】 Country industry class China USA City BEIJING ANHUI SHANGHAI NEWYORK 0 technology Semiconductor 0 1 2 3 1 technology High-speed rail 4 5 6 7 2 Serviece Tourism 8 9 10 11 3 Agriculture Vegetables 12 13 14 15 |
set_index()函数将一个或者多个列转换为行索引,返回一个新的DataFrame, 默认删除那些列,但是也可以通过drop=False参数设置保留下来 data2=data1.set_index(['industry','class']) Country China USA City BEIJING ANHUI SHANGHAI NEWYORK industry class technology Semiconductor 0 1 2 3 High-speed rail 4 5 6 7 Serviece Tourism 8 9 10 11 Agriculture Vegetables 12 13 14 15 |
stack:将数据的列“旋转”为行 unstack:将数据的行‘旋转’为列 |