[英]Iterate over a numpy array and call a method
我有個問題。 我想將日期從'2008-09-24'
為'24.09.2008'
。 我得到的是<function <lambda> at 0x000001CD2B9CE820>
。 如何遍歷host_since
並轉換日期?
host_since = npListings[:,4].astype(np.datetime64)
# host_since =
['2008-09-24' '2009-12-02' '2009-11-20' '2010-03-23' '2010-05-13'
'2010-05-13' '2010-05-25' '2010-07-23' '2009-12-22' '2010-08-08']
get_cubes = lambda x: [datetime.strptime(d, '%y-%m,%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(get_cubes)
[OUT]
<function <lambda> at 0x000001CD2B9CE82
我想要的是 get_cubes = ['24.09.2008' ... '08.08.2010'] # 也應該是一個 numpy 數組
正如@Reti43 所提到的,您不妨完全跳過 lambda。
cubes = [datetime.strptime(str(host_since[i]), '%Y-%m-%d').strftime('%d.%m.%Y')
for i in range(host_since.shape[0])]
print(cubes)
注意:如果注釋掉的host_since
變量中的數據與 numpy 數組中的實際數據相匹配,則您需要將strptime
格式更改為%Y-%m-%d
。
2分:
strptime
函數中,您的格式錯誤,應該是%Y-%m-%d
而不是%y-%m,%d
for d in range(host_since.shape[0])
迭代整數,對嗎? 那么strptime
如何工作的呢?strptime
將拋出ValueError
,因此可能還需要進行一些完整性檢查。我已將您的代碼改寫如下:
host_since =np.array(\
['2008-09-24', '2009-12-02', '2009-11-20', '2010-03-23', '2010-05-13',
'2010-05-13', '2010-05-25', '2010-07-23', '2009-12-22', '2010-08-08'])
cubes = [datetime.strptime(d, '%Y-%m-%d').strftime('%d.%m.%Y') for d in host_since]
print(cubes)
如果你想使用range
,在我看來你應該寫如下:
cubes = [datetime.strptime(host_since[d], '%Y-%m-%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(cubes)
如上所述,在這里使用 lambda 函數是不必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.