Python中利用pandas统计列表中不同元素的数量

0.前言

常见的统计python列表内不同元素个数的方法有很多,最常用的是len(set(a))这个方法,但是这个方法的问题在于a的数据类型不能是列表及其他复杂数据类型,本篇博客的目的就是为了解决这个问题。

1.使用函数

pandas.value_counts()

2.代码示例

#使用传统方法
a= [[1,2,1],[2,1,2],[2,1,1],[1,2,1]]
print(set(a))
Traceback (most recent call last):
  File "", line 1, in <module>
TypeError: unhashable type: 'list'

#使用pandas函数方法
print(pd.value_counts(a))
[1, 2, 1]    2
[2, 1, 2]    1
[2, 1, 1]    1
dtype: int64

该函数的返回值是series类型

import types
type(a)
<class 'pandas.core.series.Series'>

3.延申与拓展

一般pd.value_counts()这个方法是用在dataframe里的,用来计数具体某行或者某列的元素个数,具体索引方法与dataframe的索引方法相同,结尾加上这个函数即可

你可能感兴趣的:(pandas,python,列表)