gpt4 book ai didi

python - 根据列中的时间从文件中随机抽样行

转载 作者:行者123 更新时间:2023-11-28 19:29:27 25 4
gpt4 key购买 nike

这有点复杂,非常感谢您的帮助!我正在尝试从 .csv 文件中随机抽样行。本质上,我想要一个包含唯一位置的结果文件(位置由数据文件的 EastingNorthing 列指定,如下所示)。我想在此文件中每个 SessionDate 每 12 小时随机抽取 1 个位置(12 小时分为:06311829 小时和在 18300630 小时之间;在下面的数据文件中给出为 Start:End:);但是,如果任何 2 个位置彼此相隔 6 小时以内(基于它们的 Start: 时间),则要抛出该位置,并随机抽取一个新位置,并继续进行此采样直到没有新的位置被绘制(即不放回抽样)。我一直在尝试用 python 来做这件事,但我的经验非常有限。我尝试首先将每一行放入字典,最近将每一行放入列表,如下所示:

import random
import csv

f = open('file.csv', "U")
list = []

for line in f:
list.append(line.split(','))

我不确定从这里到哪里去 - 如何按照我需要的方式从这些列表中采样,然后将它们写入带有我的“唯一”位置的输出文件。

这是我的数据文件的前几行:

SessionDate Start:  End:    Easting Northing
27-Apr-07 18:00 21:45 174739 9785206
28-Apr-07 18:00 21:30 171984 9784738
28-Apr-07 18:00 21:30 171984 9784738
28-Apr-07 18:00 21:30 171984 9784738
28-Apr-07 18:00 21:30 171984 9784738

它变得有点复杂,因为一些观察跨度午夜,所以它们可能在不同的日期,但彼此可以在 6 小时内(这就是为什么我有这个标准),例如:

SessionDate Start:  End:    Easting Northing
27-Apr-07 22:30 23:25 171984 9784738
28-Apr-07 0:25 1:30 174739 9785206

最佳答案

这是我的解决方案 - 我对您的数据做了一些更改(位置以便更容易观察结果)。我基本上创建了一个日期 dict 指向另一个 dict 的位置,它指向选定行的列表。

data  = """SessionDate Start:  End:    Easting Northing
27-Apr-07 18:00 21:45 A 1
27-Apr-07 18:00 21:30 G 2
28-Apr-07 18:00 21:30 B 2
28-Apr-07 18:00 21:30 B 2
28-Apr-07 18:00 21:30 B 2
29-Apr-07 8:00 11:30 C 3
29-Apr-07 20:00 21:30 C 3
29-Apr-07 20:00 21:30 C 3
30-Apr-07 8:00 10:30 D 4
30-Apr-07 16:00 17:30 E 5
30-Apr-07 14:00 21:30 F 6
30-Apr-07 18:00 21:30 F 6
"""

selected = {}
for line in data.split("\n"):
if "Session" in line:
continue
if not line:
continue

tmp = [x for x in line.split() if x]
raw_dt = " ".join([tmp[0], tmp[1]]).strip()
curr_dt = datetime.strptime(raw_dt, "%d-%b-%y %H:%M")
loc = (tmp[-2], tmp[-1])

found = False
for dt in selected:
diff = dt - curr_dt
if dt < curr_dt:
diff = curr_dt - dt
# print dt, curr_dt, diff, diff <= timedelta(hours=12), loc, loc in selected[dt]
if diff <= timedelta(hours=12):
if loc not in selected[dt]:
selected[dt].setdefault(loc, []).append(tmp)
found = True
else:
found = True
if not found:
if curr_dt not in selected:
selected[curr_dt] = {}
if loc not in selected[curr_dt]:
selected[curr_dt][loc] = [tmp,]

# if output needs to be sorted
rows = sorted(x for k in selected for l in selected[k] for x in selected[k][l])
for row in rows:
print " ".join(row)

关于python - 根据列中的时间从文件中随机抽样行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com