pycharm 如何从csv文件中分别打印多列的计数?

wqlqzqxt  于 7个月前  发布在  PyCharm
关注(0)|答案(2)|浏览(73)

我需要打印列名和每个值在其中出现的次数。数据集有6个不同的列,我需要它打印3个,“Source”,“Destination”和“Protocol”,每个按降序排列。我在这里搜索,我能找到的只是有人想打印一列,我需要它打印3。这里是file
我已经让它打印了我需要的所有列和一个计数,但我认为它是打印所有列的计数,我需要为每一列单独计数,我不知道如何让它做到这一点。我试着把每个标题周围的括号,但没有工作。这是我有:

import pandas as pd
from collections import Counter

unitnine_dataset = 'IN300_Unit9.csv'
unitnine_dataset = pd.read_csv(unitnine_dataset, sep=',',
                      decimal='.', header='infer')

df = pd.DataFrame(unitnine_dataset)
count = df[['Source', 'Destination', 'Protocol']].value_counts(ascending=False)

print(count)

字符串

kcrjzv8t

kcrjzv8t1#

pandas计算列的值,使用value_counts()

def count_unique_values(df, col):
    return df[[col]].value_counts(ascending=False) #count columns values

list_of_cols = ['Source', 'Destination', 'Protocol']
for col in list_of_cols:
    print(count_unique_values(df, col))

字符串

5n0oy7gb

5n0oy7gb2#

您可能希望通过某种字典来累积计数,其中键是您感兴趣的列和单个Counter()对象的值。
以下是概念验证:

import csv
import io
import collections

test_data = """
name,col1,col2
a,1,1a
b,2,b2
c,1,b2
""".strip()

columns_meta = {}
with io.StringIO(test_data) as file_in: ## simulare open()
    for row in csv.DictReader(file_in):
        for key, value in row.items():
            columns_meta.setdefault(key, collections.Counter())[value] += 1

for col, val in columns_meta.items():
    print(f"column: {col}")
    for value, count in val.most_common():
        print(f"\t{value}: {count}")

字符串
这应该给你给予:

column: name
        a: 1
        b: 1
        c: 1
column: col1
        1: 2
        2: 1
column: col2
        b2: 2
        1a: 1

相关问题