我正在使用"import_csv“加载csv文件。假设我有一个文件如下所示。
mycsvfile.csv:
col1, col2
1, date(01-01-2015)然后使用"import_csv“加载该文件,结果如下:
Set = Couplets('col1', '1'), Couplets('col2', 'date(01-01-2015)')现在,我想检查正确的联对对象(即日期)是否介于两个日期之间,比如01-01-2014和01-01-2016,并返回false或true。
换句话说,如果我有。
twodates = Set(Couplet('firstdate',read_date('1/1/2014')), Couplet('seconddate',read_date('1/1/2016')))
print(twodates)
onedate = Couplet('twodates', read_date('1/1/2015'))我想要检查一次右对联是否在两个右对联之间,两个对联的日期。
如果你需要更多的解释,请告诉我。
发布于 2015-09-18 19:55:02
下面是我使用的import和一些样本CSV数据。(您应该能够复制/粘贴并执行以下代码)。
from datetime import datetime, date
from io import StringIO
from algebraixlib.io.csv import import_csv
from algebraixlib.mathobjects import Set, Couplet
import algebraixlib.algebras.sets as sets
import algebraixlib.algebras.clans as clans
# Sample CSV as a string
mycsvfile = """col1,col2
1,date(01-01-2015)
2,date(01-01-2018)
3,date(04-01-2015)"""首先,将CSV信息导入Python对象,而不是字符串。
def read_date(date_str: str) -> datetime:
return datetime.strptime(date_str, 'date(%m-%d-%Y)').date()
# The read_date helper imports the date(...) strings as Python date objects
data_clan = import_csv(StringIO(mycsvfile), {'col1': int, 'col2': read_date})以下是数据代数转换(作为一个家族):
{{('col1'->1), ('col2'->datetime.date(2015, 1, 1))}, {('col1'->2), ('col2'->datetime.date(2018, 1, 1))}, {('col1'->3), ('col2'->datetime.date(2015, 4, 1))}}下面是一个函数record_in_range,如果记录(作为关系)在日期范围内,则返回True。注意:这个家族中的每个关系都是一个来自左->右的函数;这就启用了rel(left_value)语法。
assert clans.is_functional(data_clan)
def record_in_range(rel):
date_value = rel('col2').value # .value extracts the raw literal from the Atom
return date(2014, 1, 1) < date_value < date(2016, 1, 1)这可以与sets.restrict操作配对,将您的家族过滤为范围内的记录。
only_in_range = sets.restrict(data_clan, record_in_range)
print(only_in_range)输出:
{{('col1'->1), ('col2'->datetime.date(2015, 1, 1))}, {('col1'->3), ('col2'->datetime.date(2015, 4, 1))}}在您的问题中,您已经在关系twodates中对日期范围进行了编码。下面的代码从那里提取日期值,而不是在record_in_range函数中硬编码它们。
twodates = Set(Couplet('firstdate', date(2014, 1, 1)), Couplet('seconddate', date(2016, 1, 1)))
def between_two_dates(rel):
return twodates('firstdate').value < rel('col2').value < twodates('seconddate').value
only_in_range = sets.restrict(data_clan, between_two_dates)
print(only_in_range)输出与上述相同。
希望这能有所帮助!
https://stackoverflow.com/questions/32653374
复制相似问题