1

所以我有这个 csv 文件,一个列看起来像这样:

1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728

现在我需要计算一个数字出现的频率。我需要这个来用 matplotlib 制作图形图片。所以图形将显示一个数字发生了多少(在这种情况下它是一个事件 id)

到目前为止,我只有打印该行的代码...

my_reader = csv.reader(open(csvpath))
for col in my_reader:
      print col[3]

我如何计算该特定列中的数字出现的频率?

4

4 回答 4

3

只需创建从数字到计数的映射。该collections.Counter()课程使这变得最简单:

import collections

counts = collections.Counter()
for row in my_reader:
    counts[row[3]] += 1

使用 acollections.defaultdict也是一种选择:

counts = collections.defaultdict(int)
for row in my_reader:
    counts[row[3]] += 1

或者您可以使用普通的dict

counts = {}
for row in my_reader:
    counts[row[3]] = counts.get(row[3], 0) + 1
于 2012-12-03T13:13:50.977 回答
1

您可以使用简单的字典。

my_reader = csv.reader(open(csvpath))
my_dict = {}
for row in my_reader:
    try:
        my_dict[row[3]] += 1
    except KeyError:
        my_dict[row[3]] = 0
于 2012-12-03T13:25:20.560 回答
1

此代码将计算总行数,如果您想要特定行,则在打印语句之前使用 if 条件并检查 if count==row_number exa: if count==3: 并获取总数。

         reader=csv.reader(open("first.csv"))
         count=0;
         for row in reader:
             count+=1
             print "total no in row "+str(count)+" is "+str(len(row))
             for i in row:
                 print i
于 2012-12-03T14:02:41.527 回答
1

您可以使用它pandas来读取数据、计算值并绘制它。Pandas 在幕后使用numpymatplotlib实现了这一点。 read_csv并且绘图命令也适用于多列。

In [29]: df = pd.read_csv('data.csv', names=['my_data']) 

In [30]: counts = df['my_data'].value_counts()

In [31]: counts
Out[31]: 
1022     3
1042     3
1040     3
1035     3
11728    3
1036     2

In [32]: counts.plot(kind='barh')
Out[32]: <matplotlib.axes.AxesSubplot at 0x4f7f510>

价值计数

于 2012-12-03T20:03:30.563 回答