如何根据列计算唯一项?

2024-05-15 01:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python获取csv列中唯一项的计数。你知道吗

我有许多CSV文件。每个CSV文件包含5列(无标题):

'AB', 'asd', 'asd2', 'asd3', 'asd4'
'AB', 'asd', 'asd2', 'asd3', 'asd4'
'AB', 'poi', 'poi2', 'poi3', 'poi4'
'BG', 'put', 'put2', 'put3', 'put4'
'BG', 'asd', 'asd2', 'asd3', 'asd4'
'BG', 'poi', 'poi2', 'poi3', 'poi4'

我想要的是从每个文件中取前两列

'AB', 'asd'
'AB', 'asd'
'AB', 'poi'
'BG', 'put'
'BG', 'asd'
'BG', 'poi'

然后根据1列计算第2列的唯一项。所以结果应该是:

'AB': 2   # AB has unique values 'asd' and 'poi'
'BG': 3   # BG has unique vales 'put', 'asd' and 'poi'

Tags: 文件csvabputbghasuniquepoi
1条回答
网友
1楼 · 发布于 2024-05-15 01:25:32

如果您可以使用第三方lib,那么一个好的选择就是使用^{}。你知道吗

这将为您提供一个pandas.DataFrame,您可以在其中选择所需的列,然后使用^{}。你知道吗

这可能看起来像:

import pandas as pd

df = pd.read_csv(...)     # specify 'filename', 'delimiter' and other info
print(df)
print(df['col_name'].value_counts())    # 'col_name' depends on how you opened the file

相关问题 更多 >

    热门问题