【发布时间】:2016-02-19 19:29:41
【问题描述】:
我有一个 csv 文件,其中包含以下格式的数据。
Layer relative_time Ht BSs Vge Temp Message
57986 2:52:46 0.00m 87 15.4 None CMSG
20729 0:23:02 45.06m 82 11.6 None BMSG
20729 0:44:17 45.06m 81 11.6 None AMSG
我想读取这个 csv 文件并计算每小时的平均值 BSs。我的 csv 文件非常大,大约有 2000 个值。但是,这些值并不是每小时均匀分布的。例如
我有237 samples from hour 3 and only 4 samples from hour 6。另外我应该提到BSs可以从多个来源收集。值始终在20-100之间。因此,它给出了一个倾斜的结果。对于每个小时,我都在计算该小时的BSs 的总和除以该小时的样本数。
主要目的是了解BSs 如何随时间演变。
但是解决这个问题的常用方法是什么。这是人们应用标准化的地方吗?如果有人可以解释如何在这种情况下应用规范化,那就太好了。
我用于处理的代码如下所示。我相信下面的代码是正确的。
#This 24x2 matrix will contain no of values recorded per hour per hour
hours_no_values = [[0 for i in range(24)] for j in range(2)]
#This 24x2 matrix will contain mean bss stats per hour
mean_bss_stats = [[0 for i in range(24)] for j in range(2)]
with open(PREFINAL_OUTPUT_FILE) as fin, open(FINAL_OUTPUT_FILE, "w",newline='') as f:
reader = csv.reader(fin, delimiter=",")
writer = csv.writer(f)
header = next(reader) # <--- Pop header out
writer.writerow([header[0],header[1],header[2],header[3],header[4],header[5],header[6]]) # <--- Write header
sortedlist = sorted(reader, key=lambda row: datetime.datetime.strptime(row[1],"%H:%M:%S"), reverse=True)
print(sortedlist)
for item in sortedlist:
rel_time = datetime.datetime.strptime(item[1], "%H:%M:%S")
if rel_time.hour not in hours_no_values[0]:
print('item[6] {}'.format(item[6]))
if 'MAN' in item[6]:
print('Hour found {}'.format(rel_time.hour))
hours_no_values[0][rel_time.hour] = rel_time.hour
mean_bss_stats[0][rel_time.hour] = rel_time.hour
mean_bss_stats[1][rel_time.hour] += int(item[3])
hours_no_values[1][rel_time.hour] +=1
else:
pass
else:
if 'MAN' in item[6]:
print('Hour Previous {}'.format(rel_time.hour))
mean_bss_stats[1][rel_time.hour] += int(item[3])
hours_no_values[1][rel_time.hour] +=1
else:
pass
for i in range(0,24):
if(hours_no_values[1][i] != 0):
mean_bss_stats[1][i] = mean_bss_stats[1][i]/hours_no_values[1][i]
else:
mean_bss_stats[1][i] = 0
pprint.pprint('mean bss stats {} \n hour_no_values {} \n'.format(mean_bss_stats,hours_no_values))
从0 to 23开始的小时,每小时的价值数如下。
[31, 117, 85, 237, 3, 67, 11, 4, 57, 0, 5, 21, 2, 5, 10, 8, 29, 7, 14, 3, 1, 1, 0, 0]
【问题讨论】:
-
我强烈建议您使用 pandas 数据框来解决您的问题。
-
@user2393267 - 我看不出使用任何软件包如何解决我描述的特定问题。
标签: csv python-3.x numpy pandas average