使用 python 计算每个地址在数据文件中出现的次数

Count how many times each address appear in data file using python

我想使用 python 计算每个地址在数据文件中出现的次数。 地址范围不固定,这意味着地址范围与每个数据文件不同。 min 和 max 之间的一些地址根本没有出现。 (第二列是地址。)

要有效解决这个问题,我该如何处理? 我不知道哪种数据结构可以,哪个函数对它有帮助?

我只是尝试使用大数组,其中索引表示地址。读取数据文件并对array[address]加1。这是糟糕的代码。

已添加: 我试过pieces_write[1].value_counts(),结果是

 print(pieces_write[1].value_counts())
 AttributeError: 'list' object has no attribute 'value_counts'

数据文件示例(第二列是地址)

 0       303567       3584       Write       0.000000
 1       55590       3072       Write       0.000000
 0       303574       3584       Write       0.026214
 1       240840       3072       Write       0.026214
 1       55596       3072       Read       0.078643
 0       303581       3584       Write       0.117964
 1       55596       3072       Write       0.117964
 0       303588       3584       Write       0.530841
 1       55596       3072       Write       0.530841
 0       303595       3584       Write       0.550502
 1       240840       3072       Write       0.550502
 1       55602       3072       Read       0.602931
 0       303602       3584       Write       0.648806
 1       55602       3072       Write       0.648806
 0       303609       3584       Write       0.910950
 1       55602       3072       Write       0.910950
 0       303616       3584       Write       0.930611
 1       240840       3072       Write       0.930611
 1       55608       3072       Read       0.983040
 0       303623       3584       Write       1.028915
 1       55608       3072       Write       1.028915
 0       303630       3584       Write       1.330380
 1       55608       3072       Write       1.330380

读取数据文件的代码

for line in open(datafile):
    line_data = line.split()
    if int(line_data[1]) < 6000000:
        if line_data[3] == 'Read':
            pieces_read.append(line_data)
            x_read.append(count)
        else:
            pieces_write.append(line_data)
            x_write.append(count)
        x_tot.append(count) 
        pieces_tot.append(line_data)
        count += 1

IIUC,你可以像这样用 pandas 来做:

import pandas as pd

df = pd.read_csv('Data_File_Path', sep='\s+', header=None, usecols=[1])
df[ df[1] < 6000000 ][1].value_counts()

输出:

55608     3
55602     3
55596     3
240840    3
303581    1
303609    1
303574    1
303567    1
303630    1
303595    1
303623    1
55590     1
303588    1
303602    1
303616    1
Name: 1, dtype: int64

你可以使用 collections.Counter:

from collections import Counter 

words = []

for line in open('data.txt'):
  # Your logic here
  words.append(line.split()[1])

words_dict = Counter(words)

for key, value in words_dict.items():
  print(key, value)

输出:

303574 1
55596 3
303630 1
303567 1
303595 1
303616 1
240840 3
303588 1
55590 1
303623 1
303602 1
303581 1
55608 3
303609 1