python中的Count()函数

count()函数之详解   https://blog.csdn.net/JNingWei/article/details/78308815

转载了count()函数,以便自己以后更好的查阅。

自己在写代码时想要获取List的个数,发现了因该使用len(),而不是C#中直接用的Count(),因此做个笔记!

转载,侵删

string 中 某字符 的次数

str.count(sub, start= 0,end=len(string))

Args Annotations
sub 搜索的子字符串
start 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

list 中 某元素 的次数

list.count(obj)

Args Annotations
obj 搜索的list

实验代码

string 中 某字符 的次数


  
  
  1. # coding=utf-8
  2. string = 'Hello World ! Hello Python !'
  3. print "string.count(sub) : ", string.count( 'H')
  4. print "string.count(sub, 1) : ", string.count( 'H', 1)
  5. print "string.count(sub, 1, 100) : ", string.count( 'H', 1, 100) # 随便取个 无限大的 end 参数

打印结果:

string.count(sub) :  2
string.count(sub, 1) :  1
string.count(sub, 1, 100) :  1

list 中 某元素 的次数


  
  
  1. list = [ 10, 20, 30, 'Hello', 10, 20]
  2. print "list.count('Hello') : ", list.count( 'Hello')
  3. print "list.count(10) : ", list.count( 10)

打印结果:

list.count('Hello') :  1
list.count(10) :  2

pandas 的value_counts()函数可以对Series里面的每个值进行计数并且排序。

现有一个DataFrame

如果我们想知道,每个区域出现了多少次,可以简单如下:

每个区域都被计数,并且默认从最高到最低做降序排列。

如果想用升序排列,可以加参数ascending=True:

如果想得出的计数占比,可以加参数normalize=True:

空值是默认剔除掉的。value_counts()返回的结果是一个Series数组,可以跟别的数组进行运算。

value_count()跟透视表里(pandas或者excel)的计数很相似,都是返回一组唯一值,并进行计数。这样能快速找出重复出现的值。

size()和shape () 是numpy模块中才有的函数

size():计算数组和矩阵所有数据的个数 
a = np.array([[1,2,3],[4,5,6]]) 
np.size(a),返回值为 6 
np.size(a,1),返回值为 3

shape ():得到矩阵每维的大小 
np. shape (a),返回值为 (2,3)

另外要注意的是,shape和size既可以作为函数,也可以作为ndarray的属性 
a.size,返回值为 6, 
a.shape,返回值为 (2,3)

				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									if(typeof window.localStorage === "object" && typeof window.csdn.anonymousUserLimit === "object"){
										if(!window.csdn.anonymousUserLimit.judgment()){
											window.csdn.anonymousUserLimit.Jumplogin();
											return false;
										}else if(!currentUserName){
											window.csdn.anonymousUserLimit.updata();
										}
									}
									
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>
发布了8 篇原创文章 · 获赞 16 · 访问量 4万+

count()函数之详解   https://blog.csdn.net/JNingWei/article/details/78308815

猜你喜欢

转载自blog.csdn.net/knkn123/article/details/85122464
今日推荐