Pandas 
Pandas是Python中基于提供高性能易用数据类型和分析工具的第三方库。
其基于Numpy实现 
名称来源于面板数据(Panel Data)和数据分析(Data Analysis) 
提供2种最基本的数据类型:Series(一维数组)和DataFrame(二维数组) 
 
安装pandas库:(在Anaconda Prompt中实现)
 
查看Pandas的版本:
1 2 import  pandas as  pd pd.__version__  
 
常用参考手册:
 
concat() 
拼接DataFrame;将数据根据不同的轴作简单的融合 
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,        keys=None, levels=None, names=None, verify_integrity=False)
axis:需要合并的轴
=0是行(列对齐,合并行) 
=1是列(行对齐,合并列) 
 
 
join:连接的方式 
inner:得到多表的交集 
outer:得到多表的并集 
ignore_index:无视表的索引,会自动根据列字段对齐,然后进行合并 
keys:说明数据源(分组键) 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 df1 = pd.DataFrame({'A' : ['A0' , 'A1' , 'A2' , 'A3' ],                     'B' : ['B0' , 'B1' , 'B2' , 'B3' ],                     'C' : ['C0' , 'C1' , 'C2' , 'C3' ],                     'D' : ['D0' , 'D1' , 'D2' , 'D3' ]}) df2 = pd.DataFrame({'A' : ['A4' , 'A5' , 'A6' , 'A7' ],                     'B' : ['B4' , 'B5' , 'B6' , 'B7' ],                     'C' : ['C4' , 'C5' , 'C6' , 'C7' ],                     'D' : ['D4' , 'D5' , 'D6' , 'D7' ]}) df3 = pd.DataFrame({'A' : ['A8' , 'A9' , 'A10' , 'A11' ],                     'B' : ['B8' , 'B9' , 'B10' , 'B11' ],                     'C' : ['C8' , 'C9' , 'C10' , 'C11' ],                     'D' : ['D8' , 'D9' , 'D10' , 'D11' ]}) frames = [df1, df2, df3] result = pd.concat(frames)   result 
 
添加参数keys,说明数据源(分组键)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 result = pd.concat(frames, keys=['x' , 'y' , 'z' ]) result 
 
也可通过字典来传入分组键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 pieces = {'x' : df1, 'y' : df2, 'z' : df3} pd.concat(pieces) 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 df1 = pd.DataFrame({'A' : ['A0' , 'A1' , 'A2' , 'A3' ],                     'B' : ['B0' , 'B1' , 'B2' , 'B3' ],                     'C' : ['C0' , 'C1' , 'C2' , 'C3' ],                     'D' : ['D0' , 'D1' , 'D2' , 'D3' ]}) df4 = pd.DataFrame({'B' : ['B2' , 'B3' , 'B6' , 'B7' ],                     'D' : ['D2' , 'D3' , 'D6' , 'D7' ],                     'F' : ['F2' , 'F3' , 'F6' , 'F7' ]}) pd.concat([df1, df4], axis=1 )   
 
join=inner:返回index的交集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 df4 = pd.DataFrame({'B' : ['B2' , 'B3' , 'B6' , 'B7' ],                     'D' : ['D2' , 'D3' , 'D6' , 'D7' ],                     'F' : ['F2' , 'F3' , 'F6' , 'F7' ]}) df4.index = [2 ,3 ,6 ,7 ] df1 df4 pd.concat([df1, df4], axis=1 , join='inner' ) 
 
join_axes指定用于对齐的轴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 df1 df4 pd.concat([df1, df4], axis=1 , join_axes=[df1.index]) pd.concat([df1, df4], axis=1 , join_axes=[df4.index]) 
 
ignore_index:无视表的索引,会自动根据列字段对齐,然后进行合并
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 df1 df4 pd.concat([df1, df4], axis=1 , ignore_index=True ) 
 
cut() 
将数组按区间划分
1 2 3 4 5 6 7 8 9 10 11 12 cut(数据数组, 面元数组)   cut(数据数组, 面元个数, precision=2 )   import  pandas as  pdages = [23 , 45 , 21 , 15 , 24 , 54 , 36 , 48 , 57 , 86 , 61 , 45 ]   cat2 = pd.cut(ages, 5 )   cat2 
 
指定面元标签:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import  numpy as  npimport  pandas as  pdages = np.random.randint(18 , 89 , size = 30 ) ages df = pd.DataFrame() df['age' ] = ages bins = [0 , 6 , 12 , 18 , 45 , 69 , 100 ] df['age_bin' ] = pd.cut(df['age' ], bins) df.head() df['age_category' ] = pd.cut(df['age' ], bins,    labels=['婴幼儿' , '少儿' , '青少年' , '青年' , '中年' , '老年' ]) df.head().append(df.tail())   
 
.codes 
查看数据对应的面元编号
1 2 3 4 5 6 7 8 9 10 import  pandas as  pdages = [23 , 45 , 21 , 15 , 24 , 54 , 36 , 48 , 57 , 86 , 61 , 45 ]   bins = [0 ,18 , 30 , 40 , 50 , 65 ,100 ]   cat = pd.cut(ages, bins) cat   
 
.value_counts() 
不同面元里含有的数据个数
1 2 3 4 5 6 7 8 cat.value_counts()   
 
DataFrame() 
DataFrame是二维数组(即数据框),是表格型数据结构
包含一组有序的列,每列可以是不同的值类型 
DataFrame有行索引和列索引 
可以看作是由多个Series组成的字典 
若没有指定索引,会自动加上索引(从0开始) 
 
DataFrame():创建二维数组(数据框)。 
DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
index :指定行索引(可以缺省) 
columns:指定列名 
 
1 2 3 4 5 6 7 8 9 10 import  numpy as  npimport  pandas as  pdfrom  pandas import  DataFramedata1 = {'Name' :['Jane' , 'John' , 'Mike' , 'Jack' ],         'Gender' :['F' , 'M' , 'M' , 'M' ],         'Age' :[18 , 19 , 21 , 17 ],         'Grade' :[89 , 90 , 87 , 76 ]} df1 = DataFrame(data1) 
 
1 2 3 4 5 6 dict2 = {'Neth' :{2010 :3.4 , 2013 :5.2 },         'Norway' :{2010 :2.5 , 2011 :3.4 , 2012 :2.8 , 2013 :4.3 }         } df4 = DataFrame(dict2) 
 
1 2 df2 = DataFrame(data1, columns=['Name' , 'Grade' , 'Gender' , 'Age' ]) 
 
访问某一列:
1 2 3 4 5 6 7 8 9 df1['Age' ] df1.Age  
 
访问某几列:
1 2 df1[['Name' , 'Age' , 'Gender' ]] 
 
astype() 
转换列格式
1 2 3 4 5 6 df[col] = df[col].astype('object' ) df[col] = df[col].astype('category' ) 
 
at[] 
通过行标签 和列标签 ,选取DataFrame中的某个元素
1 2 3 4 5 6 dict1 = {'Name' :['Mike' , 'John' , 'Maria' , 'Jack' ],         'Gender' :['M' , 'M' , 'F' , 'M' ],         'Age' :[21 , 19 , 24 , 18 ]} df1 = DataFrame(data=dict1) df1.at[2 , 'Name' ] 
 
.columns 
查看DataFrame的列名
 
 
del 
删除列数据
 
.describe 
查看数据概况
 
.describe() 
数据DataFrame的描述性统计
count:计数 
mean:均值 
std:标准差 
min:最小值 
25%:25%分位数 
50%:中位数 
75%:75%分位数 
max:最大值 
 
 
.drop() 
删除行或列
默认按行删除(即axis=0) 
axis=1 或 axis=“columns” 表示按列删除 
若要直接修改DataFrame,不保持原样,则令参数 inplace=True。 
 
按行删除:
1 2 3 4 5 df1.drop([2 ])   df1.drop([1 ,3 ]) 
 
按列删除:
1 2 3 4 df1.drop(['Gender' , 'Age' ], axis=1 ) df1.drop(['Gender' , 'Age' ], axis='columns' ) 
 
1 2 df1.drop(['Gender' ], axis=1 , inplace=True ) 
 
dropna() 
删除含缺失值的行
fillna() 
填补缺失值
 
head() 
预览前5行
可以通过赋值df.head(n)中n来调整预览的行数 
 
 
.iloc[] 
通过行号 索引行数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 data1 = {'Name' :['Jane' , 'John' , 'Mike' , 'Jack' ],         'Gender' :['F' , 'M' , 'M' , 'M' ],         'Age' :[18 , 19 , 21 , 17 ],         'Grade' :[89 , 90 , 87 , 76 ]} df3 = DataFrame(data=data1, index=['one' , 'two' , 'three' , 'four' ] df3.iloc[2 ] df3.iloc[[0 ,2 ]] 
 
获取多行数据:
 
获取单列数据:
 
获取多列数据:
 
.index 
查看DataFrame的行索引/标签
 
isin() 
用于选择DataFrame中符合条件的行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import  pandas as  pdimport  numpy as  npdates = pd.date_range("20130101" , periods=6 ) dates df = pd.DataFrame(np.random.randn(6 , 4 ), index=dates, columns=list ("ABCD" )) df["E" ] = ["one" , "one" , "two" , "three" , "four" , "three" ] df.head() df[df["E" ].isin(["two" , "four" ])] 
 
isna() 
判断数据是否缺失
1 2 pd.isna(df2["one" ]) df.isna() 
 
注意:
1 2 3 4 5 6 None  == None np.nan == np.nan 
 
对于datetime64类型数据,NaT表示缺失值。
.ix[] 
通过行号  / 行标签  索引行数据。是.loc[]和.iloc[]的结合。
1 2 3 4 5 6 7 8 9 10 11 12 13 df3.ix[3 ] df3.ix['four' ] 
 
.loc[] 
通过行标签 索引行数据。
1 2 3 4 5 6 7 8 df3.loc['three' ]   df3.loc[['two' , 'four' ]]   
 
获取多行数据:
 
获取单列数据:
1 2 df3.loc[:, 'Age' ]   df3.loc[:, ['Age' ]]   
 
获取多列数据:
 
melt() 
pivot_table()的反向操作
参数id_vars:不变的列 
参数var_name:“列转行”的列名 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 cheese = pd.DataFrame(     {         "first" : ["John" , "Mary" ],         "last" : ["Doe" , "Bo" ],         "height" : [5.5 , 6.0 ],         "weight" : [130 , 150 ],     } ) cheese cheese.melt(id_vars=["first" , "last" ]) cheese.melt(id_vars=["first" , "last" ], var_name="quantity" ) 
 
merge() 
合并DataFrame
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import  pandas as  pddf1 = pd.DataFrame([['a' , 10 , '男' ], ['b' , 11 , '女' ], ['a' , 10 , '女' ]],                     columns=['name' , 'age' , 'gender' ]) df1 df2 = pd.DataFrame([['a' , 10 , '男' ]],                    columns=['name' , 'age' , 'gender' ]) df2 df = pd.merge(df1, df2, on=['name' , 'age' ]) df df = pd.merge(df1, df2, on=['name' , 'age' , 'gender' ]) df df = pd.merge(df1, df2, on=['name' , 'age' , 'gender' ], how='outer' ) df 
 
notna() 
判断数据是否非缺失
 
.replace() 
替换DataFrame中的元素
1 2 3 4 5 6 7 8 rp_dict = {   'A' : '1' ,   'B' : '2' ,   'C' : '3'  } df['Replaced_Col' ] = df['Replaced_Col' ].replace(rp_dict) 
 
sort_index() 
按照轴排序
1 2 3 df.sort_index(axis=1 , ascending=False )  df.sort_index(by='B' )  
 
.T 
转置
tail() 
预览最后5行
可以通过赋值df.tail(n)中n来调整预览的行数 
 
 
to_csv() 
将DataFrame保存(输出)为csv文件 
df.to_csv("filename.csv", index=False, encoding='utf_8_sig')
index=False:不输出索引(默认为true) 
encoding:编码
 
 
to_excel() 
将DataFrame保存(输出)为Excel文件 
df.to_excel("filename.xlsx", index=False, sheet_name="sheet_name")
to_numpy() 
将DataFrame转换为数组Array
.values 
查看DataFrame的数据
 
修改列值 
1 2 3 4 df3['Grade' ] = (91 , 93 , 89 , 79 ) df3['Age' ] = pd.Series([16 , 25 ], index=['one' , 'three' ]) 
 
添加新列 
1 2 3 4 df3['Class' ] = (2 , 3 , 1 , 2 ) df3['Female' ] = df3.Gender=='F'  
 
 
 
date_range() 
取一定的日期范围
参数freq:
freq='D':按天 
freq='H':按小时 
freq=Q-DEC:季度的最后一天 
 
 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import  pandas as  pddt = pd.date_range('2021-08-01' , periods=5 , freq='D' ) dt hours = pd.date_range('2021-08-01' , periods=5 , freq='H' ) hours quarts = pd.date_range('2021-08-01' , periods=5 , freq='Q' ) quarts qa = pd.date_range('2021-08-01' , periods=5 , freq='2M' ) qa 
 
ExcelWriter() 
将数据批量导入Excel文件
1 2 3 4 5 6 7 8 9 import  pandas as  pdwriter = pd.ExcelWriter('file_name.xlsx' ) df1.to_excel(writer, sheet_name='sheet_name1' , index=False , encoding='utf_8_sig' ) df2.to_excel(writer, sheet_name='sheet_name2' , index=False , encoding='utf_8_sig' ) df3.to_excel(writer, sheet_name='sheet_name3' , index=False , encoding='utf_8_sig' ) writer.save() 
 
factorize() 
将类别变量/特征数字化。
Pandas中的factorize()可以将类别型变量转换为一组数字,相同的类别对应相同的数字。 
factorize()函数的返回值是一个元组(tuple),元组中含有两个元素:
第一个元素是array,其中的元素是类别型变量对应的数字; 
第二个元素是Index,是所有没有重复的类别元素。 
 
以iris鸢尾花数据为例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import  pandas as  pdfrom  urllib.request import  urlretrieveurlretrieve(url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" ,            filename="iris.data" ) iris = pd.read_csv("iris.data" , header=None ) iris.columns = ['Sepal_length' , 'Sepal_width' , 'Petal_length' , 'Petal_width' , 'class' ] iris.head() iris['class' ] = pd.factorize(iris['class' ])[0 ] iris.head() iris.tail() 
 
get_dummies() 
将类别变量one-hot encoding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import  pandas as  pdimport  numpy as  npdf = pd.DataFrame({'A' : ['F' , 'F' , 'M' , 'F' , 'M' ],                    'B' : ['one' , 'three' , 'two' , np.nan, 'one' ],                    'C' : ['1' , '2' , '1' , '3' , '2' ]}) print (df)print (pd.get_dummies(df))  print (pd.get_dummies(df, prefix=['col1' , 'col2' , 'col3' ]))print (pd.get_dummies(df['B' ], dummy_na=True ))
 
isnull() 
判断目标中是否是缺失值/缺失数据
若为缺失数据,则返回True;否则返回False。 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import  pandas as  pddict1 = {'new' :2.3 , 'old' :3.5 , 'then' :6.5 , 'obj' :8.4 } ind1 = ['new' , 'after' , 'old' , 'then' , 'obj' , 'six' ] s4 = Series(dict1, index=ind1) pd.isnull(s4) 
 
notnull() 
判断是否不是缺失数据
若为缺失数据,则返回False;否则返回True。 
与isnull()结果完全相反。 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 import  pandas as  pddict1 = {'new' :2.3 , 'old' :3.5 , 'then' :6.5 , 'obj' :8.4 } ind1 = ['new' , 'after' , 'old' , 'then' , 'obj' , 'six' ] s4 = Series(dict1, index=ind1) pd.notnull(s4) 
 
pivot_table() 
绘制透视表,进行分组统计。 
pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')
参数aggfunc:决定统计类型
 
参数fill_value:缺失值填补 
参数index:指定“行”维度 
参数columns:指定“列”维度 
使用reset_index()可以将MultiIndex变换为每行Index 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import  pandas as  pdimport  numpy as  npdf = pd.DataFrame({"A" : ["foo" , "foo" , "foo" , "foo" , "foo" ,                          "bar" , "bar" , "bar" , "bar" ],                    "B" : ["one" , "one" , "one" , "two" , "two" ,                          "one" , "one" , "two" , "two" ],                    "C" : ["small" , "large" , "large" , "small" ,                          "small" , "large" , "small" , "small" ,                          "large" ],                    "D" : [1 , 2 , 2 , 3 , 3 , 4 , 5 , 6 , 7 ],                    "E" : [2 , 4 , 5 , 5 , 6 , 6 , 8 , 9 , 9 ]}) df.head() table = pd.pivot_table(df, values='D' , index=['A' , 'B' ],                     columns=['C' ], aggfunc=np.sum ) table table = pd.pivot_table(df, values=['D' , 'E' ], index=['A' , 'C' ],                     aggfunc={'D' : np.mean,                              'E' : np.mean}) table 
 
qcut() 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 cat3 = pd.qcut(ages, 5 ) cat3 cat3.value_counts()   cat4 = pd.qcut(ages, 3 )   cat4 cat4.value_counts() 
 
Series() 
Series是一维数组(即向量)。
由一组数组(Numpy数据类型)和一组与之相关的数据标签(索引)组成 
表现形式:索引在左边,值在右边 
索引可以不用指定,会自动创建一个从0开始、到n-1结束的整数型索引。(这里n是数据的长度) 
可以通过Series的values属性和index属性获取其表现形式和索引对象 
Series对象本身及其索引(index)都有一个name属性 
索引可以通过赋值进行修改。 
 
Series():创建一维数组。 
Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
data:指定数据 
index:指定索引(可以缺省) 
name:指定数组名称 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import  numpy as  npimport  pandas as  pdfrom  pandas import  Series, DataFrame
 
1 2 3 4 5 6 7 8 9 10 11 s2 = Series([2 , 3.5 , 6.3 , 6 , 7 , np.nan],             index=['td' , 'ad' , 'rm' , 'ed' ,'way' , 'moon' ]) print (s2)
 
1 2 3 4 5 6 7 8 9 dict1 = {'new' :2.3 , 'old' :3.5 , 'then' :6.5 , 'obj' :8.4 } s3 = Series(dict1) s3 
 
1 2 3 4 5 6 7 8 9 10 11 12 ind1 = ['new' , 'after' , 'old' , 'then' , 'obj' , 'six' ] s4 = Series(dict1, index=ind1) s4 
 
.index 
查看Series的索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 s.index s2['rm' ] s2[['ed' , 'way' , 'moon' ]] s2[s2 > 4.3 ]   'way'  in  s2s4.index = ['one' , 'two' , 'three' , 'four' , 'five' , 'six' ] s4 
 
.name 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 s4 s4.name = 'New_name'  s4.index.name = 'Index_name'  s4 
 
.values 
查看Series的值
1 2 3 4 5 s.values 6.3  in  s2.values
 
 
 
 
参考资料