简体   繁体   English

CSV选择多个列

[英]CSV selecting multiple columns

I have this CSV file whereby it contain lots of information. 我有这个CSV文件,其中包含很多信息。 I have coded a program which are able to count what are inside the columns of 'Feedback' and the frequency of it. 我编写了一个程序,该程序能够计算“反馈”列中的内容及其频率。

My problem now is that, after I have produced the items inside 'Feedback' columns, I want to specifically bring out another columns which tally to the 'Feedback' columns. 现在的问题是,在“ Feedback”列中生成项目之后,我要专门显示另一个与“ Feedback”列相符的列。

Some example of the CSV file is as follow: CSV文件的一些示例如下:

Feedback      Description    Status
Others        Fire Proct     Complete
Complaints    Grass          Complete
Compliment    Wall           Complete
...           ...            ...

With the frequency of the 'Feedback' columns, I now want to show, let's say if I select 'Complaints'. 现在,以“反馈”列的频率为例,假设我选择了“投诉”。 Then I want everything that tally with 'Complaints' from Description to show up. 然后,我希望显示与Description中的“投诉”相符的所有内容。

Something like this: 像这样:

Complaints    Grass
Complaints    Table
Complaints    Door
...           ...

Following is the code I have so far: 以下是我到目前为止的代码:

import csv, sys, os, shutil
from collections import Counter

reader = csv.DictReader(open('data.csv'))
result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column,[]).append(value)

list = []
for items in result['Feedback']:
    if items == '':
        items = items
    else:
        newitem = items.upper()
        list.append(newitem)

unique = Counter(list)

for k, v in sorted(unique.items()):
    print k.ljust(30),' : ', v

This is only the part whereby it count what's inside the 'Feedback' Columns and the frequency of it. 这只是它计算“反馈”列中的内容及其频率的部分。

You could also store a defaultdict() holding a list of entries for each category as follows: 您还可以存储defaultdict() ,其中包含每个类别的条目列表,如下所示:

import csv
from collections import Counter, defaultdict

with open('data.csv', 'rb') as f_csv:
    csv_reader = csv.DictReader(f_csv)

    result = {}
    feedback = defaultdict(list)

    for row in csv_reader:
        for column, value in row.iteritems():
            result.setdefault(column, []).append(value)
        feedback[row['Feedback'].upper()].append(row['Description'])

data = []

for items in result['Feedback']:
    if items == '':
        items = items
    else:
        newitem = items.upper()
        data.append(newitem)

unique = Counter(data)

for k, v in sorted(unique.items()):
    print "{:20} : {:5}  {}".format(k, v, ', '.join(feedback[k]))

This would display your output as: 这会将您的输出显示为:

COMPLAINTS           :     2  Grass, Door
COMPLIMENT           :     2  Wall, Table
OTHERS1              :     1  Fire Proct

Or on multiple lines if instead you used: 或多行(如果改为使用):

    print "{:20} : {:5}".format(k, v)
    print '  ' + '\n  '.join(feedback[k])

When using the csv library, you should open your file with rb in Python 2.x. 使用csv库时,应在Python 2.x中使用rb打开文件。 Also avoid using list as a variable name as this overwrites the Python list() function. 还要避免将list用作变量名,因为这会覆盖Python list()函数。

Note: It is easier to use format() when printing aligned data. 注意:打印对齐的数据时,使用format()更容易。

You can do it with the code at the very end of this snippet, which is derived from the code in your question. 您可以使用此代码段末​​尾的代码来完成此操作,该代码段是从您的问题中的代码派生的。 I modified how the file is read by using a with statement which insures that it is closed when it's no longer needed. 我通过使用with语句修改了文件的读取方式,该语句可确保不再需要文件时将其关闭。 I also changed the name of the variable named list you had. 我还更改了您具有的名为list的变量的名称。 because it hides the name of the built-in type and is considered by most to be a poor programming practice. 因为它隐藏了内置类型的名称,并且大多数人认为这是不好的编程习惯。 See PEP 8 - Style Guide for Python Code for more on this and related topics. 有关此主题和相关主题的更多信息,请参见PEP 8-Python代码样式指南

For testing purposes, I also added a couple more rows of 'Complaints' type of 'Feedback' items. 为了进行测试,我还添加了几行'Complaints'类型的'Feedback'项目。

import csv
from collections import Counter

with open('information.csv') as csvfile:
    result = {}
    for row in csv.DictReader(csvfile):
        for column, value in row.iteritems():
            result.setdefault(column, []).append(value)

items = [item.upper() for item in result['Feedback']]
unique = Counter(items)

for k, v in sorted(unique.items()):
    print k.ljust(30), ' : ', v

print
for i, feedback in enumerate(result['Feedback']):
    if feedback == 'Complaints':
        print feedback, '  ', result['Description'][i]

Output: 输出:

COMPLAINTS                      :  3
COMPLIMENT                      :  1
OTHERS                          :  1

Complaints    Grass
Complaints    Table
Complaints    Door

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM