gpt4 book ai didi

python - 在 numpy.where 中访问对象方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:58 25 4
gpt4 key购买 nike

我有一个 numpy 数组中的数据(从 .csv 文件中读取)。 np.genfromtxt 的相关摘录是:

dtype = [("Category", "|S10"),
("Status", "|S11"),
("Date_start", object),
("Date_stop", object)],
names=True,
converters={2:lambda d:datetime.strptime(d, "%d/%m/%y"),
3:lambda d:datetime.strptime(d, "%d/%m/%y")}
)

一切正常,只有一个异常(exception)——访问日期时间对象的元素。以下两行代码返回的正是我所期望的:

print inp['Date_start'][1].month #returns 7
print np.where(inp['Category'] == '"R5"') #returns an array of matching indices

但下面的代码行抛出一个 AttributeError: 'numpy.ndarray' object has no attribute 'month'

print np.where(inp['Date_start'].month == 7)

这意味着我无法根据事情发生的月份返回结果,而我需要这样做。

有什么方法可以从 np.where 获得我想要的行为吗?

最佳答案

您可以定义一个矢量化属性 getter :

def func(a):
return a.month

vfunc = np.vectorize(func)

然后使用:

np.where(vfunc(inp['Date_start']) == 7)

关于python - 在 numpy.where 中访问对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078298/

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