【问题标题】:Python CSV - Need to Group and Calculate values based on one keyPython CSV - 需要根据一个键对值进行分组和计算
【发布时间】:2011-07-16 18:49:20
【问题描述】:

我有一个简单的 3 列 csv 文件,我需要使用 python 根据一个键对每一行进行分组,然后平均另一个键的值并返回它们。文件是标准的csv格式,这样设置;

ID, ZIPCODE, RATE
1, 19003, 27.50
2, 19003, 31.33
3, 19083, 41.4
4, 19083, 17.9
5, 19102, 21.40

所以基本上我需要做的是计算该文件中每个唯一邮政编码 col[1] 的平均速率 col[2] 并返回结果。因此,获取 19003、19083 等所有记录的平均速率。

我研究过使用 csv 模块并将文件读入字典,然后根据邮政编码 col 中的唯一值对字典进行排序,但似乎没有任何进展。

感谢任何帮助/建议。

【问题讨论】:

  • 到目前为止你有什么,它怎么不工作?
  • “我已经研究过使用 csv 模块并将文件读入字典,然后根据 zipcode col 中的唯一值对字典进行排序,但似乎没有任何进展。”到目前为止一切都很好。发布您遇到问题的代码。如有疑问,请将事情分解成更小的步骤,并首先对这些小部分进行编码。请张贴代码。
  • 可能是个愚蠢的问题,但是所有逗号分隔的值都在一行上,还是每行 3 列一行?

标签: python csv


【解决方案1】:

我已经记录了一些步骤来帮助澄清事情:

import csv
from collections import defaultdict

# a dictionary whose value defaults to a list.
data = defaultdict(list)
# open the csv file and iterate over its rows. the enumerate()
# function gives us an incrementing row number
for i, row in enumerate(csv.reader(open('data.csv', 'rb'))):
    # skip the header line and any empty rows
    # we take advantage of the first row being indexed at 0
    # i=0 which evaluates as false, as does an empty row
    if not i or not row:
        continue
    # unpack the columns into local variables
    _, zipcode, level = row
    # for each zipcode, add the level the list
    data[zipcode].append(float(level))

# loop over each zipcode and its list of levels and calculate the average
for zipcode, levels in data.iteritems():
    print zipcode, sum(levels) / float(len(levels))

输出:

19102 21.4
19003 29.415
19083 29.65

【讨论】:

  • @samplebias, @cmaynard 我在我的数据上使用了这个,它返回ValueError: too many values to unpack (expected 3)。知道可能出了什么问题吗?
  • @Ana,你可能连续有两个很多项目,这里预计三个:_, zipcode, level = row
  • @cmaynard 是的,我有一张包含多列的大桌子。但我只是想以与这个问题类似的方式对它们进行分组。
  • 如果我想按多个值而不是一个邮政编码进行分组,我该怎么办?
【解决方案2】:

通常,如果我必须进行复杂的阐述,我会使用 csv 来加载关系数据库表中的行(sqlite 是最快的方法),然后我会使用标准的 sql 方法来提取数据并计算平均值:

import csv
from StringIO import StringIO
import sqlite3

data = """1,19003,27.50
2,19003,31.33
3,19083,41.4
4,19083,17.9
5,19102,21.40
"""

f = StringIO(data)
reader = csv.reader(f)

conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''create table data (ID text, ZIPCODE text, RATE real)''')
conn.commit()

for e in reader:
    e[2] = float(e[2])
    c.execute("""insert into data
          values (?,?,?)""", e)

conn.commit()

c.execute('''select ZIPCODE, avg(RATE) from data group by ZIPCODE''')
for row in c:
    print row

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2013-03-27
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多