初识机器学习(pandas)

pandas初识

  • Series
  1. 定义

Series 可以看做一个定长的有序字典。基本任意的一维数据都可以用来构造 Series 对象:

	import pandas as pd
    s=pd.Series([1,2,3,4,5,6])
    print(s)
    0    1
    1    2
    2    3
    3    4
    4    5
    5    6
  1. 属性

Series 对象包含两个主要的属性:index 和 values,分别为上例中左右两列。

	s = Series(data=[1,3,5,7],index = ['a','b','x','y'])
	s
    a    1
    b    3
    x    5
    y    7

Series 对象和它的 index 都含有一个 name 属性:

	s.name = 'a_series'
	s.index.name = 'the_index'
	s
    the_index
    a            1
    b            3
    x            5
    y            7
    Name: a_series, dtype: int64
  • DataFrame
  1. 定义

DataFrame 是一个表格型的数据结构,它含有一组有序的列(类似于 index),每列可以是不同的值类型(不像 ndarray 只能有一个 dtype)。基本上可以把 DataFrame 看成是共享同一个 index 的 Series 的集合。

  1. 简单示例

>data = {'state':['Ohino','Ohino','Ohino','Nevada','Nevada'],
  'year':[2000,2001,2002,2001,2002],
  'pop':[1.5,1.7,3.6,2.4,2.9]}
  1. 完整构造器

DataFrame(data=None,index=None,coloumns=None)

	data=[[1,2,3],[5,6,7],[11,12,13],[4,5,6],[7,8,9]]
	df=pd.DataFrame(data,index=['one','two','three','four','five'],columns=['year','state','pop'])
  1. 特点与操作

DataFrame 面向行和面向列的操作基本是平衡的,任意抽出一列都是 Series

	//定义数据
	date=np.arange(12).reshape(3,4)
	df=pd.DataFrame(date,index=['x','y','z'],columns=['a','b','c','d'])

以下标的方式获取行,只能是序列

	df[:2]  
	 a  b  c  d  
	 x  0  1  2  3 
	 y  4  5  6  7
	 //注:当为df[0]时会报错

选择行,以标签名的形式,只能是序列,包含最后一个元素

	df['x':'z']  
	a  b   c   d  
	x  0  1   2   3  
	y  4  5   6   7  
	z  8  9   10  11  

选择列,若一列则类型为Series

	 df.a  
	 x    0  
	 y    4  
	 z    8

 df['a']  
 x    0  
 y    4  
 z    8  

	 df[['a','b']]  
	  	a  b  
	  x  0  1  
	  y  4  5  
	  z  8  9  

选择行时

	df.loc['x']  
	a    0  
	b    1 
	c    2  
	d    3  

df.loc[['x','y'],['a','b']]  
 	a  b  
 x  0  1  
 y  4  5  

df.loc['x',['a','b']]  
a    0  
b    1  

使用位置选择

df.iloc[1:3,2:4] //取1,2行,2,3列
 	c   d  
y   6   7  
z   10  11  

df.iloc[:,1]  //第一列
 c
x   2
z   10

df.iloc[1,:] //取一行的所有列
a    4
b    5
c    6
d    7

混合使用标签和位置

df.ix[1] //取第一行
df.ix[:2,[‘a’,‘b’]]//取第二行,与’a’,‘b’列

使用bool参数

 df[df>5]=99  
  df  
  	a   b   c   d  
 x  0   1   2   3  
 y  4   5   99  99  
 z 99  99   99  99  
  1. 增删改

修改某一列

dff['a']=5  
dff  
   a  b c  d  
1  5  1  2  3  
2  5  5  6  7  
3  5  9  10 11  

修改某一列

df['a']=[5,6,4]
 dff
    a  b  c  d  
 x  5  1  2  3  
 y  6  5  6  7  
 z  4  9 10  11 

添加某一列

data=[2,3,10]  
dff['e']=data  
 dff  
     a b  c  e 
 1  5  1  2 2  
 2  5  5  6 3  
 3  5  9  10 10  

删除某一列

del dff['d']  
dff  
   a  b  c  
1  5  1  2  
2  5  5  6  
3  5  9  10 

对columns进行排序

	df2  
    a  b  c  d  
    1  0  1  2  3  
    2  4  5  6  7  
    3  8  9  10  11  

df2.sort_index(axis=1,ascending=False)  
	 	    d  c  b  a  
	 	1  3  2  1  0  
	 	2  7  6  5  4  
	 	3  11 10 9  8  

对index进行排序

df2.sort_index(axis=0,ascending=False)  
    a  b  c  d  
3  8  9  10  11  
2  4  5  6   7  
1  0  1  2   3  

对某列进行排序

df2.sort_values(by='b')
    a  b  c  d  
1  0  1  2   3  
2  4  5  6   7  
3  8  9  10  11  
  1. 统计和筛选

	df  
	   a  b  c  d  
	1  0  1  2  3  
	2  4  5  6  7  
	3  8  9  10  11  

找寻最小值

df.a.min()  

筛选符合条件的行

df[df.a>=4] 
   a  b   c  d  
2  4  5  6  7  
3  8  9  10  11 

index在(1,3)之间的行

f[(df.index>1) & (df.index<3)]  
   a  b  c  d 
2  4  5  6  7  

pivot_table

df.pivot_table(index="year",values="state",aggfunc=np.mean)
//或
df.pivot_table(index="year",values=['state','pop'],aggfunc=np.mean)

apply

def plus(df,n,m):
df['c'] = (df['a']+df['b']) * m
df['d'] = (df['a']+df['b']) * n
return df
list1 = [[1,3],[7,8],[4,5]]
df1 = pd.DataFrame(list1,columns=['a','b'])
df1 = df1.apply(plus,axis=1,args=(2,3,))
print(df1)
//默认情况下 将表格中的每列传入方法中,此处将每行传入方法中
  1. 分组

	>>> df=pd.DataFrame({'a':[1,2,2,3,3,4],'b':[2,3,4,4,1,4],'c':[2,3,2,2,3,8]})  
	>>> df  
	   a  b  c  
	0  1  2  2  
	1  2  3  3  
	2  2  4  2  
	3  3  4  2  
	4  3  1  3  
	5  4  4  8  
//按照某一列进行分组,显示每个组内行的个数  
>>> df.groupby('a').count()  
   b  c  
a        
1  1  1  
2  2  2  
3  2  2  
4  1  1 
//对组内的每一列求和  
>>> df.groupby('a').sum()  
   b  c  
a        
1  2  2  
2  7  5  
3  5  5  
4  4  8  
//显示组内某一列的和 
>>> df.groupby('a').b.sum()  
a  
1    2  
2    7  
3    5  
4    4  
  1. 合并

concat

concat函数是在pandas底下的方法,可以将数据根据不同的轴作简单的融合
pd.concat(objs, axis=0, join=‘outer’, join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False)
参数说明:
objs: series,dataframe或者是panel构成的序列lsit
axis: 需要合并链接的轴,0是行,1是列
join:连接的方式 inner,或者outer

相同字段的表首尾相接

n=np.array([1,2,5,3,76,5,3,5,8,42,1,95]).reshape(3,4)
n1=pd.DataFrame(n)
n2=pd.DataFrame([[66,77,88,99]])
c=pd.concat([n1,n2])
print(c)
   0   1   2   3
0 1   2   5   3
1 76   5   3   5
2  8   42   1  95
0  66   77  88  99

横向表拼接是只需要指定轴为1即可

加上join参数的属性,如果为’inner’得到的是两表的交集,如果是outer,得到的是两表的并集。

c=pd.concat([n1,n2],axis=1,join='inner')
  0  1  2  3  0  1   2   3
0 1  2  5  3  66  77  88  99
1 76  5  3  5  11  22  33  44

如果有join_axes的参数传入,可以指定根据那个轴来对齐数据 ;如下保留指定的n1表的轴,然后将n2的表与之拼接

c=pd.concat([n1,n2],axis=1,join=‘inner’,join_axes=[n2.index])

	    0  1  2  3  0  1   2  3
	0   1  2  5  3  66  77  88  99
	1   76  5  3  5  11  22  33  44

添加ignore_index=True属性后,新形成的表会更新索引
append append是series和dataframe的方法,使用它就是默认沿着列进行拼接(axis = 0,列对齐)

***merge

df1=pd.DataFrame({'key':['a','b','c','e'],'data1':range(4)})
df2=pd.DataFrame({'key':['a','b','d'],'data2':range(3)})
//df1和df2根据key进行内连接  
>>> pd.merge(df1,df2,on='key')  
     data1    key  data2  
0      0   a      0  
1      1   b      1  
//若要连接的列名不同,可以显式指定 
df3=pd.DataFrame({'key3':['a','b','c','e'],'data1':range(4)})  
df4=pd.DataFrame({'key4':['a','b','d'],'data2':range(3)}) 
pd.merge(df3,df4,left_on='key3',right_on='key4') 
data1 key3  data2 key4  
0    0    a      0    a 
1    1    b      1    b 
//外连接
 pd.merge(df1,df2,on='key',how='outer')  
     data1 key  data2  
 0    0.0   a    0.0  
 1    1.0   b    1.0  
 2    2.0   c    NaN  
 3    3.0   e    NaN  
 4    NaN   d    2.0  
 //显示连接的情况
 pd.merge(df1,df2,on='key',how='outer',indicator=True)  
     data1  key  data2    _merge  
 0    0.0   a    0.0   both  
 1    1.0   b    1.0    both  
 2    2.0   c    NaN   left_only  
 3    3.0   e    NaN   left_only  
 4    NaN   d    2.0   right_only  
 //利用多个键进行合并 
 left_df=pd.DataFrame({'key1':['a','b','c'],'key2':['d','e','f'],'lval':[1,2,3]})  
 right_df=pd.DataFrame({'key1':['a','r','c'],'key2':['d','e','f'],'rval':[4,5,6]})  
 pd.merge(left_df,right_df,on=['key1','key2'])
     key1 key2  lval  rval  
 0    a    d     1     4  
 1    c    f     3     6 
 pd.merge(left_df,right_df,on=['key1','key2'],how='outer')
     key1 key2  lval  rval  
 0    a    d   1.0   4.0  
 1    b    e   2.0   NaN  
 2    c    f   3.0   6.0  
 3    r    e   NaN   5.0  

猜你喜欢

转载自blog.csdn.net/weixin_42150936/article/details/84931037