4

我有一个包含 4 列 {Tag、User、Quality、Cluster_id} 的 csv 文件。使用 python 我想做以下事情:对于每个 cluster_id(从 1 到 500),我想查看每个用户的好标签和坏标签的数量(从质量列获得)。有超过6000个用户。我只能在 csv 文件中逐行读取。因此,我不确定如何做到这一点。

例如:

Columns of csv = [Tag User Quality Cluster]   
Row1= [bag  u1  good     1]  
Row2 = [ground u2 bad   2]  
Row3 = [xxx  u1 bad  1]  
Row4 = [bbb  u2 good 3]  

我刚刚设法获取了 csv 文件的每一行。

我一次只能访问每一行,没有两个 for 循环。我要实现的算法的伪代码是:

for cluster in clusters:  
    for user in users:  
        if eval == good:  
            good_num = good_num +1  
        else:  
            bad_num = bad_num + 1
4

2 回答 2

3

collections.defaultdict在这里应该有很大的帮助:

# WARNING: Untested
from collections import defaultdict

auto_vivificator = lambda: defaultdict(auto_vivificator)

data = auto_vivificator()

# open your csv file

for tag, user, quality, cluster in csv_file:
    user = data[cluster].setdefault(user, defaultdict(int))
    if is_good(quality):
        user["good"] += 1
    else:
        user["bad"] += 1

for cluster, users in enumerate(data):
    print "Cluster:", cluster
    for user, quality_metrics in enumerate(users):
       print "User:", user
       print quality_metrics
       print  # A blank line
于 2013-01-26T19:47:56.793 回答
2

由于有人已经发布了defaultdict解决方案,我将给熊猫一个,只是为了多样化。 pandas是一个非常方便的数据处理库。在其他不错的功能中,它可以在一行中处理此计数问题,具体取决于所需的输出类型。真的:

df = pd.read_csv("cluster.csv")
counted = df.groupby(["Cluster_id", "User", "Quality"]).size()
df.to_csv("counted.csv")

--

为了pandas方便起见,我们可以加载文件——其中的主要数据存储对象pandas称为“DataFrame”:

>>> import pandas as pd
>>> df = pd.read_csv("cluster.csv")
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 500000 entries, 0 to 499999
Data columns:
Tag           500000  non-null values
User          500000  non-null values
Quality       500000  non-null values
Cluster_id    500000  non-null values
dtypes: int64(1), object(3)

我们可以检查前几行是否正常:

>>> df[:5]
   Tag  User Quality  Cluster_id
0  bbb  u001     bad          39
1  bbb  u002     bad          36
2  bag  u003    good          11
3  bag  u004    good           9
4  bag  u005     bad          26

然后我们可以按 Cluster_id 和 User 分组,并在每个组上工作:

>>> for name, group in df.groupby(["Cluster_id", "User"]):
...     print 'group name:', name
...     print 'group rows:'
...     print group
...     print 'counts of Quality values:'
...     print group["Quality"].value_counts()
...     raw_input()
...     
group name: (1, 'u003')
group rows:
        Tag  User Quality  Cluster_id
372002  xxx  u003     bad           1
counts of Quality values:
bad    1

group name: (1, 'u004')
group rows:
           Tag  User Quality  Cluster_id
126003  ground  u004     bad           1
348003  ground  u004    good           1
counts of Quality values:
good    1
bad     1

group name: (1, 'u005')
group rows:
           Tag  User Quality  Cluster_id
42004   ground  u005     bad           1
258004  ground  u005     bad           1
390004  ground  u005     bad           1
counts of Quality values:
bad    3
[etc.]

如果您要对csv文件进行大量处理,那么绝对值得一看。

于 2013-01-26T20:46:40.953 回答