csv行中的Python计数唯一值

时间:2018-11-09 07:34:05

标签: python csv

我有一个CSV,它在列表中。 示例:

[[R2C1,R01,API_1,801,API_TEST01],
[R2C1,R01,API_1,802,API_TEST02],
[R2C1,R01,API_1,801,API_TEST03]]

喜欢在i[3]中找出所有唯一性并计数。 结果:

[{num: 801, count: 2}, {num: 802, count: 1}]

,以便我可以调用dict键进行另一项测试。

代码:

    for row in data[1:]:
    vnum = row[3]
    ipcount.append({"num":vnum,"count": count})
    if row[3] not in ipcount:
        ipcount.append({"num":vlan})

3 个答案:

答案 0 :(得分:1)

如果您使用pandas库:

import pandas as pd
# Open your file using pd.read_csv() or from your list of lists
df = pd.DataFrame([['R2C1','R01','API_1',801,'API_TEST01'],
                   ['R2C1','R01','API_1',802,'API_TEST02'],
                   ['R2C1','R01','API_1',801,'API_TEST03']])
print(df)
      0    1      2    3           4
0  R2C1  R01  API_1  801  API_TEST01
1  R2C1  R01  API_1  802  API_TEST02
2  R2C1  R01  API_1  801  API_TEST03

在这里您可以使用.value_counts()来获取3列中每个值的数量,然后使用字典理解将其转换为所需的形式:

[{'num': k, 'count': v} for k, v in dict(df[3].value_counts()).items()]
[{'num': 801, 'count': 2}, {'num': 802, 'count': 1}]

答案 1 :(得分:1)

您可以使用字典进行此操作,以便按num元素对列表项进行分组。最后一步是使用列表理解以获得所需的结果。

dict = {}
for elem in data:
  if elem[3] not in dict:
    dict[elem[3]] = 0
  dict[elem[3]] = dict[elem[3]] + 1

final_list = [{'num' : elem, 'count': dict[elem]} for elem in dict]

输出

[{'num': 801, 'count': 2}, {'num': 802, 'count': 1}]

答案 2 :(得分:0)

这里是一种纯pandas方法,没有任何循环

import pandas as pd 

# define path to data
PATH = u'path\to\data.csv'

# create panda datafrmae
df = pd.read_csv(PATH, usecols = [0,1,2,3], header = 0, names = ['a', 'b', 'c','num'])

# Add count to column of interest
df['count'] = df.groupby('num')['num'].transform('count')

# only keep unique values in column of interest
df.drop_duplicates(subset=['num'], inplace = True)

# create dict from bowth columns
your_output = dict(zip(df.num, df.count))