您的位置:首页 > 编程语言 > Python开发

Python Numpy,Pandas基础笔记

2016-09-09 14:19 537 查看

Numpy

Numpy是python的一个库。支持维度数组与矩阵计算并提供大量的数学函数库。

arr = np.array([[1.2,1.3,1.4],[1.5,1.6,1.7]])#创建ndarray时候也可以指定dtype
arr.astype(dtype = np.int) #浮点数转int
#对数组批量运算,作用在每个元素上
arr = np.array([[1,2,3],[4,5,6]])
print arr**5
#索引和切片
arr = np.array([1,2,3,4,5,6])
print arr[:2]#arr[0]和arr[1]
arr = np.array([[1,2,3],[4,5,6]])
print arr[:2] #打印第1,2行

#布尔型索引
name = ['Bob','La','CA','Da','Ea','Fa']
rnd_arr = np.random.randn(7,4)
print rnd_arr[name == 'CA']#利用布尔数组选择行,这里name == 'CA'会产生一个布尔数组
a = [1,2,3]
b = [True,False,True]
print a[b]#选第一个和第三个

#花式索引
a = [1,2,3,4,5]
index = [4,2,0]
b = a[index]
#对于二维数组
arr = np.arange(32).reshape(8,4)
print arr[[1,5,2,7],[:,0,3,1,2]] #1,5,2,7行的0,3,2,1列,如果不加冒号就是打印arr[1][0],arr[5][3]   转置 arr.T
#逻辑表述为数组运算where
x = np.random.randn(1,5)
y = np.random.randn(1,5)
cond = np.array([True,False,True,False,True])
result = np.where(cond,x,y)  #也可以省略x,y直接加条件 如 x>2 只有condition的时候返回的是复合条件的坐标索引
#where的逻辑
#如果条件1和2 则0,否则如果条件1取1,否则条件2 取2 ,再不行取3。相当于一个if else的缩写。
#列表推导result = [x if c else y for (c,x,y) in zip(cond,x,y)]

#数学和统计方法 sum,mean,std,var这些
arr = np.random.randn(5,4)
bools = np.array([False,False,True,False])

arr.mean(axis = 1) #按行取平均
print (arr>0).sum() #大于0的和
print (bools == True).sum() #True的个数
print bools.any() #有一个True 都True
print bools.all() #有一个为False 则False
unique(x)#去重 ,还有交叉并补

#高斯消元法 qr分解,此外乘法dot,求逆inv
from numpy.linalg import qr
arr = np.random.randn(5,4)
q,r = qr(arr)
print q,r
arr.mean(axis = 0) #按照列求均值,也即是竖直方向,如果axis=1则按行求均值,水平方向

#数组重塑
arr = np.arrange(8)
print arr.reshape(4,2)
#只是改变了显示方式,其实内存中的存储结构不变
#下面三种都能达到同样的效果
x = np.array([[1, 2], [3, 4]])
print x.flatten()
print x.ravel()
print x.reshape(-1)
#两者默认均是行序优先
print x.flatten('F')
print x.ravel('F')
print x.T.reshape(-1)
#flatten ravel的区别
x = np.array([[1, 2], [3, 4]])
x.flatten()[1] = 100
print x
# flatten:返回的是拷贝
x.ravel()[1] = 100
print x
#ravel则是对元素组的一个引用,会改变元素组,和reshape一样只是改变了显示方式

#连接数组
a1 = np.array([[0,1,2],[2,1,3]])
a2 = np.array([[4,5,6],[7,8,9]])
print np.concatenate([a1,a2],axis = 0) #添加行,竖直方向添加,如果axis = 1添加列,水平方向添加
print np.vstack((a1,a2)) #竖直方向叠起来
print np.hstack((a1,a2)) #水平方向叠起来 和上面的效果一样
#拆分
f,s = np.split(a2,[1,2],axis = 0) #竖直方向上,也即是按行拆分
#put,take
arr = np.arange(5)
inds = [1]
arr.put(inds,50) #替换inds位置的数
print arr arr.take([1,2]) #和花式索引效果一样


  

Pandas

pandas 处理时间序列,缺失数据的处理。

#Series 类似于一维数组,因为平时的数组都是默认索引的,Series可以指定索引。

from pandas import Series
obj = Series([4,7,-5,3],index = ['a','b','c','d'])
print obj[obj > 0] #找出大于0的
print obj.index

#字典可以直接生成Series。
locations =['NT','RT','RG','XL']
data = {'NT':4000,'RT':5000,'X':100}
obj = Series(data,index = locations)
print obj

#Series,相加相同的索引部分相加,也可以给索引以及该series命名。
#index替换
obj.index = [1,2,3,4]

#DataFrame 可以理解成二元的,他是表格型的数据结构,比如我们平常见的Excel。有行索引,列索引,可以理解成Series的合并。
from pandas import Series,DataFrame
data = {
'locations':['NT','RT','RG','XL'],
'years':[2000,2001,2004,2008],
'pop':[1.5,1.6,1.7,1.8]
}
Df = DataFrame(data, columns = ['years','locations','pop'],index = ['one','two','three','four']) #指定列
print Df

years locations  pop
one     2000        NT  1.5
two     2001        RT  1.6
three   2004        RG  1.7
four    2008        XL  1.8
#修改指定的列,可以设置索引,没有的变成NaN。
val = Series([2, 5, 7],index = ['one','two','four'])
Df['pop'] = val
print Df
years locations  pop
one     2000        NT  2.0
two     2001        RT  5.0
three   2004        RG  NaN
four    2008        XL  7.0
Df['big'] = (Df.years == 2008)

#丢弃指定轴上的项,指定索引或列
print Df.drop(['two','four'],axis = 1)
#索引,选取和过滤
#Series的切片是一个引用
import numpy as np
se = Series(np.arange(4), index = ['a','b','c','d'])
print se['b':'c']
se['b','c'] = 5
print se

#DataFrame打印列可以直接调用,打印行需要.ix
data = DataFrame(np.arange(16).reshape(4,4),index = ['a','b','c','d'],columns = ['one','two','three','four'])
print data
#print data.ix['a']
print data.ix[:'c','two'] #'two'列的a,b,c行,对于非数字索引一定是闭区间。
data[data < 5] = 0 #所有小于5的都被设置为0

#算术运算与数字对齐,对齐操作同时发生在行和列上(就是行和列都匹配),索引不对齐的地方计算就是用NA
from pandas import Series
s1 = Series([1,2,3,4,5],index = ['a','b','c','d','e'])
s2 = Series([2,3,4,5,6],index = ['a','b','c','d','f'])
print s1+s2

a    3.0
b    5.0
c    7.0
d    9.0
e    NaN
f    NaN
dtype: float64
#DataFrame比较复杂,会列出所有的行列,相当于一个并集,然后行列不匹配的那个变成NaN,所有两个DataFrame相加,可能行列大小都会变化,如果不相同的话。
df1 = DataFrame(np.arange(12).reshape(3,4),columns = list('abcd'))
df2 = DataFrame(np.arange(20).reshape(4,5),columns = list('abcde'))
print df1.add(df2,fill_value = 0) #不匹配的,用nan的地方用0填充

a     b     c     d     e
0   0.0   2.0   4.0   6.0   4.0
1   9.0  11.0  13.0  15.0   9.0
2  18.0  20.0  22.0  24.0  14.0
3  15.0  16.0  17.0  18.0  19.0
#Dataframe和Series之间 相减,默认是按照水平方向,按行,如果axis = 0,则竖直方向,按照列,每一列都减去一个Series。
#函数应用和映射,Series有个应用到元素的map方法,Dataframe有applymap
f = lambda x : x.max() - x.min()
print df1.apply(f, axis = 1)# 对水平方向的每一行最大减最小
print df1.apply(f,axis = 0) # 对竖直方向的每一列最大减最小

#applymap 应用到每一个元素
df1.astype(np.float)
f2 = lambda x: '%.2f' % x
print df1.applymap(f2)
print df1['a'].map(f2)#df['a']相当于一个Series,应用到每一个元素是map

#对列和索引进行排序,可以指定升序还是降序还有rank函数
#按照索引排序
df1.sort_index(axis = 1,ascending = False)

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

#按值排序
df1.sort_values(by = ['a','b'],ascending = False)#降序,先a按照a,a不行则b
#rank
obj = Series([7,9,-5,1,4,2,2,5])
print obj.rank()#输出的是每个元素应该在的位置

#指定列变成索引
df1.set_index(['a'])

#pandas的索引可以用重复,返回的是一个数组
#层次索引
#Series的层次索引
from pandas import Series
s = Series(np.random.randn(5), index = [['a','a','b','b','c'],[1,2,1,2,1]])
print s
print s.index
print s[:2]
print s['b':'c']
print s.unstack() #把1,2放到列上去,c只有1个就变成了NaN了,变成了DataFrame的样子。
print s.unstack().stack()

a  1   -1.050402
2    0.489801
b  1   -0.538088
2    0.886044
c  1    2.695847
dtype: float64
MultiIndex(levels=[[u'a', u'b', u'c'], [1, 2]],
labels=[[0, 0, 1, 1, 2], [0, 1, 0, 1, 0]])
a  1   -1.050402
2    0.489801
dtype: float64
b  1   -0.538088
2    0.886044
c  1    2.695847
dtype: float64
1         2
a  0.900427 -0.673935
b  0.162862 -0.118564
c  0.039270       NaN
#DataFrame的层次索引,DataFrame不管在行还是列都可以多值索引
df = DataFrame(np.arange(12).reshape((4,3)),index = [['a','a','b','b'],[1,2,1,2]],columns = [['Ohio','Chicago','NewYork'],['a','b','c']])
print df
#交换两个索引,原来在外面的变到里面,也可以根据索引排序
df.index.names = ['key1','key2']
df_df = df.swaplevel('key1','key2')
df_df.swaplevel(0,1).sortlevel(0)
#指定key统计
print df.sum(level = 'key2')
Ohio Chicago NewYork
red    blue   green
key2
1       6       8      10
2      12      14      16
#整数索引会有歧义,比如-1,0有时候不知道是位置,还是他的索引,所以避免歧义一般是.iloc


iloc,loc和ix的区别
参考自:http://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation
s = Series(np.arange(8),index = [8,9,15,1,2,3,4,5])
print s

8     0
9     1
15    2
1     3
2     4
3     5
4     6          
5     7
dtype: int32

print s.iloc[:3]
8     0
9     1
15    2
dtype: int32

print s.loc[:3]
8     0
9     1
15    2
1     3
2     4
3     5
dtype: int32
print s.ix[:,3]
8     0
9     1
15    2
1     3
2     4
3     5
dtype: int32
#可以看到.ix和.loc是相同的效果,把3当作是index当中的值,而iloc是打印的前三行。如果是s.ix[:7],s.loc[:7]这样的没有的数,就会报错,而.iloc就会打印前7行。
#如果是DataFrame,.ix可以索引,位置混合使用,索引选行,列可以取位置切片。
df = DataFrame(np.arange(12).reshape(3,4),index = list('abc'),columns = ['d','e','f','g'])
print df
print df.ix[:'c',:3]

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


 上面numpy,pandas有很多东西没说,还是要实战才容易记住,多多加油吧!


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: