knn(k-近邻)算法的过程中用到了tile函数,记录下来此函数的用法:

函数原型:numpy.tile(A,reps) #简单理解是此函数将A进行重复输出

   函数格式tile(A,reps)

  A和reps都是array_like

  A的类型众多,几乎所有类型都可以:array, list, tuple, dict, matrix以及基本数据类型int, string, float以及bool类型。

  reps的类型也很多,可以是tuple,list, dict, array, int, bool.但不可以是float, string, matrix类型。

计较常用的形式有两种,是将A简单进行一维重复输出,和将A进行二维重复后输出。

一维重复:

1 import numpy as np
2 a = [[1,2,3],[4,5,5]]
3 b = np.tile(a,3)
4 print(b)
5
6 #输出为
7 #[[1 2 3 1 2 3 1 2 3]
8 # [4 5 5 4 5 5 4 5 5]]

二维重复:#上面的一维重复相当于 b = np.tile(a,[1,3])

 1 import numpy as np2 a = [[1,2,3],[4,5,5]]3 b = np.tile(a,[2,3])4 print(b)5 6 #输出为:7 #[[1 2 3 1 2 3 1 2 3]8 # [4 5 5 4 5 5 4 5 5]9 # [1 2 3 1 2 3 1 2 3]
10 # [4 5 5 4 5 5 4 5 5]]

操作示例


>>> tile(1,2)
array([1, 1])>>> tile((1,2,3),3)
array([1, 2, 3, 1, 2, 3, 1, 2, 3])>>> tile(a,2)
array([[1, 2, 3, 1, 2, 3],[4, 5, 5, 4, 5, 5]])>>> b=[1,3,5]
>>> tile(b,[2,3])
array([[1, 3, 5, 1, 3, 5, 1, 3, 5],[1, 3, 5, 1, 3, 5, 1, 3, 5]])>>> a=[[1,2,3],[5,4]]
>>> tile(a,[2,3])
array([[[1, 2, 3], [5, 4], [1, 2, 3], [5, 4], [1, 2, 3], [5, 4]],[[1, 2, 3], [5, 4], [1, 2, 3], [5, 4], [1, 2, 3], [5, 4]]])

numpy排序、搜索和计数函数和方法:

排序Sorting

  1. sort(a[, axis, kind, order]) Return a sorted copy of an array.
  2. lexsort(keys[, axis]) Perform an indirect sort using a sequence of keys.
  3. argsort(a[, axis, kind, order]) Returns the indices that would sort an array.
  4. ndarray.sort([axis, kind, order]) Sort an array, in-place.
  5. msort(a) Return a copy of an array sorted along the first axis.
  6. sort_complex(a) Sort a complex array using the real part first, then the imaginary part.
  7. partition(a, kth[, axis, kind, order]) Return a partitioned copy of an array.
  8. argpartition(a, kth[, axis, kind, order])

python列表排序
list.sort()一般用法:list.sort(axis = None, key=lambdax:x[1],reverse = True)
或者使用内置函数sorted():

sorted(data.tolist(), key=lambda x: x[split])

[python函数: 内置函数]
用ndarray.sort内建函数排序
数组的sort()方法用于对数组进行排序,它将改变数组的内容。
ndarray.sort()没有key参数,那怎么编写比较函数comparator?
示例

list1 = [[1, 3, 2], [3, 5, 4]]
array = numpy.array(list1)
array.sort(axis=1)
print(array)[[1 2 3][3 4 5]]

sort内建函数是就地排序,会改变原有数组,不同于Python中自带的sorted函数和numpy.sort通用函数,参数也不一样。
sort内建函数返回值为None,所以不能有这样的语法:array.sort(axis=1)[:5],这相当于是对None类型进行切片操作
矩阵按其第一列元素大小顺序来对整个矩阵进行行排序
mat1=mat1[mat1[:,0].argsort()]
用numpy.sort通用函数排序
np.sort()函数则返回一个新数组,不改变原始数组(类似于python中自带的sorted函数,但numpy中没有sorted函数,参数也不一样)。
它们的axis参数默认值都为-1,即沿着数组的最后一个轴进行排序。 np.sort()函数的axis参数可以设置为None,此时它将得到平坦化之后进行排序的新数组。

>>> np.sort(a) #对每行的数据进行排序array([[1, 3, 6, 7, 9],[1, 2, 3,5, 8],[0, 4,8, 9, 9],[0, 1,5, 7, 9]])
>>> np.sort(a, axis=0) #对每列的数据进行排序 array([[5,1,1, 4, 0],[7, 1, 3, 6, 0],[9, 5, 9, 7, 2],[9, 8, 9'8, 3]])
升序排序的实现:
list1 = [[1,3,2], [3,5,4]]
array = numpy.array(list1)
array = sort(array, axis=1)   #对第1维升序排序
#array = sort(array, axis=0)   #对第0维
print(array)
[[1 2 3][3 4 5]]
降序排序的实现:
#array = -sort(-array, axis=1)   #降序
[[3 2 1][5 4 3]]

用numpy.argsort通用函数排序
argsort函数用法(numpy-ref-1.8.1P1240)
argsort()返冋数组的排序下标,axis参数的默认值为-1。
argsort(a, axis=-1, kind=’quicksort’, order=None)
Returns the indices that would sort an array.
argsort函数返回的是数组值从小到大的索引值
Examples
——–
One dimensional array:一维数组

    >>> x = np.array([3, 1, 2])>>> np.argsort(x)array([1, 2, 0])Two-dimensional array:二维数组>>> x = np.array([[0, 3], [2, 2]])>>> xarray([[0, 3],[2, 2]])    >>> np.argsort(x, axis=0) #按列排序array([[0, 1],[1, 0]])>>> np.argsort(x, axis=1) #按行排序array([[0, 1],[0, 1]])>>> x = np.array([3, 1, 2])
>>> np.argsort(x) #按升序排列
array([1, 2, 0])
>>> np.argsort(-x) #按降序排列
array([0, 2, 1])

Note: 当然也可以升序排序,在处理的时候处理成降序也行,如np.argsort(index[c])[:-MAX_K:-1]
另一种方式实现按降序排序(不能用于多维数组)

>>> a
array([1, 2, 3])
>>> a[::-1]
array([3, 2, 1])
>>> x[np.argsort(x)] #通过索引值排序后的数组
array([1, 2, 3])
>>> x[np.argsort(-x)]    #不能用于二维存取!!
array([3, 2, 1])
多维数组的降序排序
list1 = [[1, 3, 2], [3, 1, 4]]
a = numpy.array(list1)
a = numpy.array([a[line_id,i] for line_id, i in enumerate(argsort(-a, axis=1))])
print(a)[[3 2 1][4 3 1]]list1 = [[1, 3, 2], [3, 1, 4]]
a = numpy.array(list1)
sindx = argsort(-a, axis=1)
indx = numpy.meshgrid(*[numpy.arange(x) for x in a.shape], sparse=True,indexing='ij')
indx[1] = sindx
a = a[indx]
print(a)[[3 2 1][4 3 1]]list1 = [[1, 3, 2], [3, 1, 4]]
a = numpy.array(list1)
a = -sort(-a, axis=1)
print(a)[[3 2 1][4 3 1]]

搜索Searching
一般numpy数组搜索到某些值后都要进行另外一些操作(如赋值、替换)。
比如替换numpy数组中值为0的元素为1, a[a == 0] = 1
更复杂的筛选可以通过np.minimum(arr, 255)或者result = np.clip(arr, 0, 255)实现。
argmax(a[, axis, out]) Returns the indices of the maximum values along an axis.
nanargmax(a[, axis]) Return the indices of the maximum values in the specified axis ignoring NaNs.
argmin(a[, axis, out]) Returns the indices of the minimum values along an axis.
nanargmin(a[, axis]) Return the indices of the minimum values in the specified axis ignoring NaNs.
argwhere(a) Find the indices of array elements that are non-zero, grouped by element.
nonzero(a) Return the indices of the elements that are non-zero.
flatnonzero(a) Return indices that are non-zero in the flattened version of a.
where(condition, [x, y]) Return elements, either from x or y, depending on condition.
searchsorted(a, v[, side, sorter]) Find indices where elements should be inserted to maintain order.
extract(condition, arr) Return the elements of an array that satisfy some condition.
最值
用min()和max()可以计算数组的最大值和最小值,而ptp()计算最大值和最小值之间的差。
它们都有axis和out两个参数。
用argmax()和argmin()可以求最大值和最小值的下标。如果不指定axis参数,就返回平坦化之后的数组下标。

>>> np.argmax(a) #找到数组a中最大值的下标,有多个最值时得到第一个最值的下标
2
>>> a.ravel()[2] #求平坦化之后的数组中的第二个元素9
可以通过unravel_index()将一维下标转换为多维数组中的下标,它的第一个参数为一维下标值,第二个参数是多维数组的形状。
>>> idx = np.unravel_index(2, a.shape)
>>> idx
(0, 2)
>>> a[idx]
9

当使用axis参数时,可以沿着指定的轴计算最大值的下标。
例如下面的结果表示,在数组 a中,第0行中最大值的下标为2,第1行中最大值的下标为3:

>>> idx = np.argmax(a, axis=1)
>>> idx
array([2, 3, 0, 0])

使用idx选择出每行的最大值:

>>> a[xrange(a.shape[0]),idx]
array([9, 8, 9, 9])
nonzero(a)

返回非0元素的下标位置
其实不就是a != 0吗?
元素查找where
查找某个元素的位置
given a Numpy array, array, and a value, item, to search for.
itemindex = numpy.where(array==item)
The result is a tuple with first all the row indices, then all the column indices.
只查找一维array的第一个位置
array.tolist().index(1)
itemindex = np.argwhere(array==item)[0]; array[tuple(itemindex)]
Note:np.argwhere(a) is the same as np.transpose(np.nonzero(a)).The output of argwhere is not suitable for indexing arrays.For this purpose use where(a) instead.index = numpy.nonzero(first_array == item)[0][0]
[Is there a Numpy function to return the first index of something in an array?]
分段函数
{像python中的x = y if condition else z 或者 C语言里面的 condition?a:b,判断条件是否正确,正确则执行a,否则b}
where函数
where(condition, [x, y])
例1:计算两个矩阵的差,然后将残差进行平方

def f_norm_1(data, estimate):residule = 0for row_index in range(data.shape[0]):for column_index in range(data.shape[1]):if data[row_index][column_index] != 0:residule += (data[row_index][column_index] - estimate[row_index][column_index]) ** 2return residule
def f_norm_2(data, estimate) return sum(where(data != 0, (data-estimate) **2, 0))

因为我需要的是考虑矩阵稀疏性,所以不能用内置的norm,函数1是用普通的python写的,不太复杂,对于规模10*10的矩阵,计算200次耗时0.15s,函数2使用了where函数和sum函数,这两个函数都是为向量计算优化过的,不仅简洁,而且耗时仅0.03s, 快了有五倍,不仅如此,有人将NumPy和matlab做过比较,NumPy稍快一些,这已经是很让人兴奋的结果。
例2:

>>> x=np.arange(10)
>>> np.where(x<5,9-x,x)
array([9, 8, 7, 6, 5, 5, 6, 7, 8, 9]) 

表示的是产生一个数组0~9,然后得到另一个数组,这个数组满足:当x<5的时候它的值变为9-x,否则保持为x)。
select函数

out = select(condlist, choicelist, default=0)

其中,condlist是一个长度为N的布尔数组列表,choicelist是一个长度为N的储存候选值 的数组列表,所有数组的长度都为M.如果列表元素不是数组而是单个数值,那么它相当于元素值都相同且长度为M的数组。对于从0到M-1的数组下标i,从布尔数组列表中找出满足条件“condlist[j][i]=True”的 j的最小值,则“out[i]=choicelist[j][i]”,其中out是select()的返回数组。choicelist的最后一个元素为True,表示前面所有条件都不满足时,将使用choicelist的最后一个数组中的值。也可以用default参数指定条件都不满足时的候选值数组。

>>> np.select([x<2,x>6,True],[7-x,x,2*x])
array([ 7,  6,  4,  6,  8, 10, 12,  7,  8,  9]) 

表示的是当x满足第一个条件时,执行7-x,当x满足第二个条件事执行x,当二者都不满足的时候执行2*x。

piecewise()
piecewise(x, condlist, funclist)

前面两个函数都比较耗内存,所以引入piecewise(),因为它只有在满足条件的时候才计算。也就是where()和select()的所有参数都需要在调用它们之前完成计算,因此下面的实例中NumPy会计算下面4个数组:x>=c, x

np.piecewise(x, [x < 0, x >= 0], [-1, 1])
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.piecewise(x, [x<2,x>6], [lambda x:7-x,lambda x:x,lambda x:2*x])
array([7, 6, 0, 2, 4, 6, 8, 0, 1, 2]) 

Note: piecewise中funclist如果不是数值而是函数时要使用lambda表达式,不能使用简单表达式7-x,否则会出错,如ValueError: NumPy boolean array indexing assignment cannot assign 10 input values to the 2 output values where the mask is true。
[numpy.piecewise]
实例
用一个分段函数描述三角波:

def triangle_wave(x, c, c0, hc):x = x - x.astype(np.int) #三角波的周期为1,因此只取x坐标的小数部分进行计算 return np.where(x>=c,0,np.where(x<c0, x/c0*hc, (c-x)/(c-c0)*hc))

由于三角波形分为三段,因此需要两个嵌套的where()进行计算.由于所有的运算和循环 都在C语言级别完成,因此它的计算效率比frompyfunc()高。
随着分段函数的分段数量的增加,需要嵌套更多层where(),但这样做不便于程序的编写 和阅读。可以用select()解决这个问题。

def triangle._wave2(x, c, c0, hc):x = x - x.astype(np.int)return np.select([x>=c, x<c0, True], [0, x/c0*hc, (c-x)/(c-c0)*hc])

也可以使用default:return np.select([x>=c, x

def triangle_wave3(x, c, c0, hc):x = x - x.astype(np.int) return np.piecewise(x,[x>=c, x<c0],[0, # x>=clambda x: x/c0*hc, # x<c0lambda x: (c-x)/(c-c0)*hc]) # else

使用piecewise()的好处在于它只计算需要计算的值.因此在上面的例子中,表达式 “x/c0*hc”和“(c-x)/(c-c0)*hc”只对输入数组x中满足条件的部分进行计算。
调用

x = np.linspace(0, 2, 1000)
y4= triangle_wave3(x,0.6, 0.4, 1.0)

计数Counting
count_nonzero(a) Counts the number of non-zero values in the array a.
统计numpy数组中非0元素的个数。
0-1array统计1个数
统计0-1array有多少个1, 两种方式
np.count_nonzero(fs_predict_array)
fs_predict_array.sum()
count_nonzero速度更快,大概1.6倍快。
统计多维数组所有元素出现次数
使用pandas顶级函数pd.value_counts,value_counts是一个顶级pandas方法,可用于任何数组或序列:

>>> pd.value_counts(obj.values, sort=False)`

本文记录了python中numpy库中的一些函数的使用。

python中一些函数使用(tile,排序,搜索,计数)相关推荐

  1. python中lambda函数对时间排序_python – 使用lambda函数排序()

    我的字符串看起来像"co1 / co2","co3 / co4"--"co11 / co12" 将其描述为正则表达式: ^(?P\w\w)( ...

  2. python中order函数_order by排序

    作者 Toby,持牌照消费金融模型经理,发明国家算法专利,国内最大医药数据中心数据挖掘部门负责人!和重庆儿科医院,中科院教授,赛柏蓝保持慢病数据挖掘项目合作!清华大学,百度,腾讯,网易,爱奇艺等平台签 ...

  3. python中pow函数的用法_python中pow函数用法及功能说明

    幂运算是高更数学的应用学科,是一种关于幂的数学运算.同底数幂相乘,底数不变,指数相加.同底数幂相除,底数不变,指数相减.幂的乘方,底数不变,指数相乘.适用于精确计算领域. 计算机作为精确计算的一种方式 ...

  4. python set函数排序_python的set函数 Python中的set会自动排序

    python中如何在set中添加元素?语句是什么 python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), inters ...

  5. python中sorted函数的用法_Python3 中sorted() 函数的用法

    描述 sorted() 函数对所有可迭代的对象进行排序操作. 语法 sorted(iterable, key=None, reverse=False) iterable – 可迭代对象. key – ...

  6. python中groupby()函数讲解与示例_详解python中groupby函数通俗易懂

    一.groupby 能做什么? python中groupby函数主要的作用是进行数据的分组以及分组后地组内运算! 对于数据的分组和分组运算主要是指groupby函数的应用,具体函数的规则如下: df[ ...

  7. python中定义函数常用关键字_Python 中定义函数的关键字是 _________________ 。_学小易找答案...

    [其它]实验4-串和数组-实验任务书.docx [填空题]表达式 'abc' in ['abcdefg'] 的值为______________. [填空题]已知 x = range(1,4) 和 y ...

  8. Python 函数式编程,Python中内置的高阶函数:map()、reduce()、filter()与sorted(),Python中返回函数

    函数式编程 是一种编程范式,比函数更高层次的抽象. 函数式编程将计算视为函数而非指令. 纯函数式编程:不需要变量,没有副作用,测试简单. 支持高阶函数,代码简洁. Python 支持的函数式编程 不是 ...

  9. Python中匿名函数与内置高阶函数详解

    大家好,从今天起早起Python将持续更新由小甜同学从 初学者的角度 学习Python的笔记,其特点就是全文大多由 新手易理解 的 代码与注释及动态演示 .刚入门的读者千万不要错过! 很多人学习pyt ...

  10. python中format函数用法简书_从Python安装到语法基础,这才是初学者都能懂的爬虫教程...

    Python和PyCharm的安装:学会Python和PyCharm的安装方法 变量和字符串:学会使用变量和字符串的基本用法 函数与控制语句:学会Python循环.判断语句.循环语句和函数的使用 Py ...

最新文章

  1. 为图片添加半透明遮罩效果
  2. spring mvc + mybatis 框架搭建 ( idea + gradle)
  3. 人群分割--Fully Convolutional Neural Networks for Crowd Segmentation
  4. 女儿社交媒体求生日卡 美96岁失明二战老兵收海量祝福
  5. 几处早莺争暖树下一句是什么,几处早莺争暖树后一句
  6. FJ集团企业级邮件服务器构建方案
  7. Java黑皮书课后题第10章:10.4(MyPoint类)设计一个名为MyPoint的类,代表一个以x坐标和y坐标表示的点
  8. win7 下jenkins配置与使用
  9. python请输入_不断提示用户输入Python
  10. JAVA模拟肯德基点餐系统源码,肯德基辞职员工透露,用这几句暗语点餐,你拿的分量会比别人多...
  11. 用SMS2003部署Windows XP SP3:SMS2003系列之十
  12. jQuery源码研究学习笔记(二)
  13. 最小生成树之普里姆算法(Prim算法)
  14. (大一)——自学计划
  15. Android.mk宏定义demo
  16. python测量 检测软件_pytest首页、文档和下载 - Python 测试工具 - OSCHINA - 中文开源技术交流社区...
  17. 【实战】在qgis上查看街景照片( go2streetview谷歌街景、go2mapillary)
  18. 读书百客:《千秋岁·淡烟平楚》赏析
  19. Kali Linux实战:如何一下看出Windows计算机是否开启445危险端口?是否存在永恒之蓝漏洞?
  20. 新浪微相册https外链图片无法调用解决方法

热门文章

  1. unity 表面着色器、顶点、片元着色器
  2. 2017 Java开发面试题-Java Web篇(1)
  3. “C:\Windows\SysWOW64\ntdll.dll”。无法查找或打开 PDB 文件
  4. 跟着姜少学Java基础编程之八:循环结构
  5. 轻松拿下暗恋已久的学姐 (html+css+js制作520表白网页)
  6. 《炬丰科技-半导体工艺》臭氧的新型光刻胶剥离技术
  7. K210视觉体验—人脸识别
  8. app架构升级,该如何高效实用Kotlin?架构师必备技能
  9. Android程序签名详解、打包、发布到Google play步骤
  10. math_极限微分导数微商/对数函数的导函数推导(导数定义极限法)/指数函数求导公式推导(反函数求导法则/对数求导法)/导数表示法导数记号系统