ipython 未找到日期属性

ipython date attribute not found

我正在使用 ipython 笔记本 运行 使用 pandas 进行一些分析。但是,我 运行 遇到以下函数和日期属性的问题

def get_date(time_unit):
    t = tickets['purchased date'].map(lambda x: x.time_unit)
    return t

# calling it like this produces this error
get_date('week')

AttributeError: 'Timestamp' object has no attribute 'time_unit'

但这没有功能

tickets['purchased date'].map(lambda x: x.week)

我正在尝试创建函数 get_date(time_unit) 因为我稍后需要将该函数用于 get_date('week')get_date('year') 等等

我如何将传递给有效属性的字符串转换为我打算使用的函数?

谢谢。

您应该使用 getattr 按名称检索属性。

def get_date(time_unit):
    t = tickets['purchased date'].map(lambda x: getattr(x, time_unit))
    return t

get_date('week')

您所做的等同于 getattr(x, 'time_unit')

当你这样做时 -

t = tickets['purchased date'].map(lambda x: x.time_unit)

这不会替换 time_unit 字符串中的任何内容并采用 x.week ,而是会尝试采用 x 的 time_unit 属性,这会导致您的错误看到了。

您应该使用 getattr 使用属性的字符串名称从对象获取属性 -

t = tickets['purchased date'].map(lambda x: getattr(x, time_unit))

来自documentation of getattr() -

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar.