python 统计数据
时间: 2023-11-20 07:58:33 浏览: 42
以下是Python中常用的统计数据的方法和函数:
1. 列表统计
如果要统计一个列表中各元素出现的次数,可以使用Python内置的collections模块中的Counter函数。例如,对于列表[1,2,3,1,2,1],可以使用以下代码进行统计:
```python
from collections import Counter
a = [1,2,3,1,2,1]
result = Counter(a)
print(result)
```
输出结果为:Counter({1: 3, 2: 2, 3: 1})
2. 字典统计
如果要统计一个字典中各键值对出现的次数,可以使用Python内置的collections模块中的Counter函数。例如,对于字典{'a':1,'b':2,'c':1},可以使用以下代码进行统计:
```python
from collections import Counter
a = {'a':1,'b':2,'c':1}
result = Counter(a.values())
print(result)
```
输出结果为:Counter({1: 2, 2: 1})
3. Pandas统计
Pandas是Python中一个非常强大的数据分析库,可以用来进行各种数据统计和分析。例如,对于一个数据集data,如果要统计其中某个字段的不同取值的数目,可以使用以下代码:
```python
import pandas as pd
data = pd.read_csv('data.csv')
result = data['字段名'].value_counts()
print(result)
```
其中,data.csv是数据集的文件名,'字段名'是要统计的字段名。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)