- value_count() 方法
pandas 中 value_count() 是一种查看表格某列中有多少个不同值的快捷方法,并计算每个不同值在该列中有多少重复值。
注意:value_counts() 是 Series 类型的数据拥有的方法,DataFrame 类型的数据不可以直接用,需要指定对哪一行或哪一列使用(DataFrame 取某列、行之后,就是 Series 类型了)。
(参考:pandas中.value_counts()的用法)
(参考:如何统计dataframe里某一列中某个数值出现的次数)
- value_count() 和 count() 方法的区别
(1)value_count() 是 pandas.Series 的方法
(2)count() 是 list 的方法
- Tips
(1)使用 value_counts() 时,必须保证该元素在 Series 存在,否则报错:KeyError。(当然~可以使用 try-excepy 捕获 KeyError~)。
(2)如果直接对 DataFrame 类型的数据使用 value_counts() 方法,会报错:AttributeError。(当然~可以使用 try-except 捕获 AttributeError~)
修改后的代码:
import pandas as pd
import numpy as np
a = list(range(1, 51))
a_reshape = np.array(a).reshape(5, 10).T
b = pd.DataFrame(a_reshape)
print(b)
print(type(b[0])) # series 类型
try:
print(b[0].value_counts()[1])
except KeyError:
print('b中没有该元素\n')
try:
print(b.value_counts()[1])
except AttributeError:
print(''' DataFrame' object has no attribute 'value_counts\n' ''')
(参考:Python 异常处理)
(3)list 类型的统计元素个数,使用 list.count()
Original: https://blog.csdn.net/weixin_40583722/article/details/121033388
Author: Satisfying
Title: 【20211028】【Python】统计Series/List类型的数据中某元素出现的个数
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/752785/
转载文章受原作者版权保护。转载请注明原作者出处!