用python计算表格地市、CGI两列。计算每个地市中CGI不重复出现次数
时间: 2023-03-10 13:32:18 浏览: 77
你可以使用Python中的collections模块来计算每个地市中CGI不重复出现的次数。具体方法是,使用collections.Counter()函数对表格中每个地市的CGI进行计数,然后使用Counter.values()函数获取每个地市的CGI不重复出现的次数。
相关问题
怎么使用python将excle表格进行统计表格中每个姓名的出现次数
可以使用 pandas 库来读取 Excel 表格,并使用 groupby 和 count 方法来统计每个姓名的出现次数。具体实现步骤如下:
1. 安装 pandas 库:在命令行中输入 `pip install pandas`,等待安装完成。
2. 导入 pandas 库:在 Python 脚本中导入 pandas 库,代码如下:
```python
import pandas as pd
```
3. 读取 Excel 表格:使用 pandas 库中的 read_excel 方法读取 Excel 表格,代码如下:
```python
df = pd.read_excel('data.xlsx')
```
其中,data.xlsx 为待读取的 Excel 表格的文件名。
4. 统计出现次数:使用 pandas 库中的 groupby 和 count 方法统计每个姓名的出现次数,代码如下:
```python
counts = df['姓名'].groupby(df['姓名']).count().sort_values(ascending=False)
```
其中,counts 为一个 pandas Series 对象,其中每个元素对应一个姓名及其出现次数。
5. 输出结果:将结果输出为 Excel 表格或者打印出来,代码如下:
```python
counts.to_excel('counts.xlsx', index=True, header=['出现次数'])
```
其中,counts.xlsx 为输出的 Excel 表格的文件名,index=True 表示保留行索引,header=['出现次数'] 表示设置表头为 "出现次数"。
完整的代码示例如下:
```python
import pandas as pd
# 读取 Excel 表格
df = pd.read_excel('data.xlsx')
# 统计出现次数
counts = df['姓名'].groupby(df['姓名']).count().sort_values(ascending=False)
# 输出结果
counts.to_excel('counts.xlsx', index=True, header=['出现次数'])
```
其中,data.xlsx 是一个包含姓名和其他信息的 Excel 表格,'姓名' 是 Excel 表格中的一列,表示每个人的姓名。
Python如何计算列表中每个元素出现的次数
Python中可以使用collections模块中的Counter类来计算列表中每个元素出现的次数。Counter类是一个字典的子类,用来统计可哈希对象(如字符串、元组、列表等)中的元素出现的个数。
下面是一个简单的示例:
```python
from collections import Counter
lst = [1, 1, 2, 3, 3, 3, 4, 4, 5]
cnt = Counter(lst)
print(cnt)
```
输出结果为:
```
Counter({3: 3, 1: 2, 4: 2, 2: 1, 5: 1})
```
这里,Counter类接收一个列表lst作为参数,并返回一个字典,其中键为列表中的元素,值为该元素在列表中出现的次数。
如果只想获取出现次数最多的前n个元素,可以使用most_common()方法。示例如下:
```python
from collections import Counter
lst = [1, 1, 2, 3, 3, 3, 4, 4, 5]
cnt = Counter(lst)
print(cnt.most_common(2))
```
输出结果为:
```
[(3, 3), (1, 2)]
```
这里,most_common()方法接收一个整数n作为参数,返回出现次数最多的前n个元素及其出现次数的列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)